Thursday, November 6, 2014

The Internet of Us - Hardware Nowhere

Never leave your buddy behind in Houston, Texas!

The Holy Trinity of Hack

My friends and I used to joke around that there was a "holy trinity" in hacking. You had to understand software, firmware, and hardware in order to bring any value as a security researcher. I still believe that is even more true today than it has ever been. 

The Internet of Things (IoT) movement means merging these three paradigms into a more tightly bound conglomerate than ever before. Software on your cloud/laptop/desktop links to the firmware on your IoT's hardware, which transmits data upstream to the application firmware on your phone's hardware... bla bla bla

Bla, Bla, Blah!
We get it. Everything is connected. 

A Rad New Whatever

What's really cool about this movement is that we're seeing shifts in everything from architectural design to manufacturing. And the manufacturing is key. Think about the average Internet of Things concept. 

Do you want a Rad New Thing to connect your Blah to your Meh? Of course you do! Your Meh will now be IoT capable to speak to any Blah that understands Meh's protocol! 

We're connected! And it's So Special!
But, where do you pick up a Meh? With all the new IoT products that will be saturating the market in the coming years, how does one more easily go out and purchase this a device from the wild ecosystem of choices we'll have? 

I'll tell you how. You wont. The device will be made in your home. 

Get Outta Here

No, really! Have you checked out BotFactory? Their 3D printer, Squink, which survived its Kickstarter round in August, is designed to do this very thing. Sort of. 

Squink is the first step in this direction, and BotFactory clearly has the idea of home manufacturing in mind for their end game (at least they had better, or I'd be a really confused VC). 

Dog, I thought you wuz makin' serious tech, bruh... 
Squink takes 3D printing to the next level by introducing the concept of building printed circuit boards (PCBs) in the home. But, they even promise to go one step further. They state that Squink will be able to function as a Pick and Place machine as well. This means that not only will it be able to print circuit boards on demand, it will be able to place components on the board as well. 

The next step? On demand builds of hardware devices, flashed with firmware downloaded over the Internet. 

Need that Meh for your Blah? You've got it! 

But What Does It all Mean?!

If you're still wondering why this is important, think about how manufacturing affects the cost of devices that you use. Think about FoxConn in China, and the workers that have to build products for Apple. Think about the increased cost of business not only for those local economies, but for the companies that outsource from their home country overseas. Think about the massive amount of hardware trash piled up in India, Malaysia, China, and other countries that tear down and harvest the components we throw away. 

No, really....

Simplifying the manufacturing process to the homes that want the devices means the potential to change this existing model. It means decreasing the cost of manufacturing and making only one device instead of one hundred devices just so one customer can acquire that one device. That can disrupt a product's entire pricing model, ecological impact, and availability in a major way. 

This also means that hardware becomes far less important. Instead of hardware seeming like this esoteric voodoo magic box that only a small percentage of us understand, it opens up and becomes widely accessible. Why? 

Because we no longer need to care about it! Anyone will be able to build and play with their own circuit boards on demand at little cost! And they will be able to share their designs for free over the Internet instantaneously! That's incredible! 

Models Gonna Modulate

Essentially, we're on the precipice of another shift in computing. We oscillate back and forth between highlighting the importance of software, to the importance of hardware, and back. We're about to shift again. For how long? Who knows. That doesn't matter. 

What does matter is that security models will account for the upcoming change. How do we secure devices that are made on demand in the home? How will provisioning work? How will the firmware be loaded onto the new device? Can the firmware be signed and delivered over the network? If so, what does that require on the part of the 3D printer? 

There are many questions that must be answered here, and at Lab Mouse Security, we're preparing our answer. 

As always, if you have questions about IoT security, or want to engage us for a code review, please reach out to us via our Contact Page. 

Best wishes for the Internet of Us!
Don A. Bailey
Founder
Lab Mouse Security
@InfoSecMouse

Thursday, October 23, 2014

If You Haven't Pen-Tested Now, Wait

Abstinence Or Whatever

This morning, my esteemed peer Shawn Moyer referred to a blog post he wrote in September 2013 on waiting for pen-testing until Q1, but buying in Q4. He's not wrong. 

Shawn makes strong points about the money and the actual work-load on the consultant side. The fact is, teams traditionally get so swamped in Q4 that they do indeed place junior resources where they shouldn't. But, Atredis and I have one thing in common: we don't have to care about that problem. None of us are juniors. We're all principal-level consultants. Nor do we have the overhead of managing or maintaining interns to try and eek out results. 

While Shawn discusses the pen-testing team's side of the fence, I'm discussing the client's issues with scheduling a penetration test in Q4. If you haven't purchased a pen-testing engagement already, you should schedule the test for Q1. 

There Goes E911

Q4 isn't just the most lucrative time of year for tech companies, it's the most profitable time of year for most companies. As a result, everyone is on high alert to manage their resources as effectively as possible. This means not focusing on organizational security in the event of an emergency. Case in point? 

Intrado, the company that manages the majority of the United States' E911 service had their system fail for over 11 million people across seven states, including the entire state of Washington. No one could make a 911 call during that time period. Intrado happens to be based here in Colorado, and I happen to have personal experience with them. The fact is, they're an exceptional company and I have been impressed by their above-average engineering expertise. 

Regardless, how do you think the organization - that is one of the country's only third-party 911 contractors - would have reacted if this event occurred during Q4? During Black Friday? During Christmas? God forbid, during Devil's Night? The security and engineering teams would be completely re-tasked toward assessing an event like this, why it occurred, how to remediate it, whether a bad actor was involved, etc. Any penetration test at this point would - and should - immediately stop. 

Point being, whether you're managing E911 infrastructure for the entire country, or simply building a web service that caters to hundreds of thousands of engineers world-wide, prioritization is key. Losing customers is never an acceptable choice. When resources are constrained during an already busy time of year, priorities must align with the business' key goals, and nothing else. 

Schedule Effectively 

So, if you're considering buying penetration services now, don't. Why? It's already going to be the last week of October. Buying services now generally means 
  • one to three weeks of sales process
  • a week or two of scheduling resources on both sides
  • actual engagement: anywhere from 2 days to 2 weeks (on average)
If you're buying services now, this puts your actual engagement starting date anywhere from November 10th to December 1st. If you're on the light side of a test and only need a couple days of effort, you're still looking at remediation through one of the busiest holiday seasons in the country: Thanksgiving. If you're on the heavy side of the test, you're going to be running into mid-December. That means the week of Dec. 15th your team will be scrambling to remediate security issues during *the* busiest two holidays in the world: Christmas and New Year's Day! 

Any critical event during this time means that the results of any penetration test must be put off until the critical event has passed. On average, any overlapping operations/engineering/security event takes between one week to a month to evaluate, remediate, and monitor. During this already swamped time of year, that means that the results of any penetration test will be ignored for up to two months if a critical event occurs adjacent to a common vacation or holiday period. This is a total waste of money! 

Don't Kill Money!

The only value of a penetration test has is when the results can be used within an effective period of time. This means weeks after the penetration test has occurred. Otherwise, because of the increased amount of security risks being identified in modern times, any penetration test performed today will have drastically different results than one performed a month from now. 

Remember ShellShock? Heartbleed? Cisco's ASA flaws? LZ4? SSLv3 POODLE? We're seeing more and more game changing flaws coming out, and security teams are already flooded with a To Do list longer than Santa's naughty list. 

Scheduling a pen-test during Q4 is basically asking to be put on Santa's naughty list for knowingly booking an engagement whose output can't be fully utilized in an effective time frame. Don't do it! Don't kill money!

Sure, spend the money today. Book the team. Get the most effective engagement for your budget and your organization's needs. But, schedule it for a time when the output of the engagement will bring the most value to your organization. That, typically, means Q1. 

So, if you want the most value out of a security review, check out Lab Mouse. Even check out Atredis. Book a team that is going to maximize your investment by providing you with only top-tier talent, but only schedule the engagement when the timing makes sense for your organization. 

Hey, Intrado, if you need someone that specializes in mobile/embedded/Erlang/telco to help you with a security or code review of your E911 system, give me a shout. I'll give you a good deal since you're local and I already love ya. 

Best,
Don A. Bailey
Founder
Lab Mouse Security

Tuesday, October 21, 2014

GoLang Debugging - Turning Pennies Into G's

GDB Ain't Great

Our favorite application debugger is awesome. Don't get me wrong, I use it often. Almost daily. But, the fact remains that GDB is dependent on a predefined legacy application architecture. GDB wasn't designed to predict new application architectures. As a result, it isn't elegant at supporting alternatively designed stacks, concurrency models, or execution flows. 

That's essentially why GDB has been enhanced with extension capabilities like Sequences, Guile, and yes, even Python. Unfortunately, even the extension system is a bit lacking. Case in point? The existing GoLang GDB script uses a completely outdated extension API that causes exceptions. It wasn't super useful to begin with, either. 

donb@evian-les-bains:~/home/library/golang/go/src/pkg/regexp$ GOMAXPROCS=9 /usr/bin/gdb -q ./regexp.test
Reading symbols from ./regexp.test...done.
Loading Go Runtime support.
(gdb) run
Starting program: /home/donb/home/library/golang/go/src/pkg/regexp/regexp.test 
^C
Program received signal SIGINT, Interrupt.
runtime.usleep () at /home/donb/home/library/golang/go/src/pkg/runtime/sys_linux_amd64.s:77
77              RET
(gdb) info goroutines 
Python Exception <class 'gdb.error'> Attempt to extract a component of a value that is not a (null).: 
Error occurred in Python command: Attempt to extract a component of a value that is not a (null).
(gdb) 
In the above example, we see a common debugging scenario that's been going on for over a year or two. The debugging process is even documented on the GoLang website under Debugging Go Code With GDB. Yet, when one tries to reproduce the steps outlined in the documentation, the above error occurs. 

Why does this happen? The runtime-gdb.py script packaged with GoLang uses an outdated model for accessing gdb.Value objects, essentially treating them as dictionaries. Because the internals of the gdb.Value no longer support this model, or allow linking via Python generators in the fashion used in the script, simple commands will fail.

Go Routine Yourself

To solve these horrors, we really just need to generate a class that handles retrieval of pertinent values from the GoLang runtime environment. For those not in the know, each GoLang application acts like a kernel, scheduling the execution of each Go routine, monitoring memory allocations, and preparing for garbage collection.

Before you start to become concerned about potentially severe user-land bloat, take a moment to realize that this is actually the correct architecture. Any robust production quality application must handle resources elegantly by silently monitoring for operating system signals, scheduling and managing thread synchronization, handling per-thread intercommunication, and efficiently allocating and deallocating subsystem resources transparently. GoLang accomplishes all these things, but with surprising eloquence and a new level of light-weight that even Magdalena Frackowiak would be jealous of.

GoLang executes in tiny self-contained executable images called Go Routines, which are co-routines handled by GoLang's internal scheduler. GoRoutines are not threads, they are simple co-routines that execute under an Operating System thread. The benefit of this is that GoRoutines can move transparently across OS threads (pthread, libthread (Solaris), etc) with almost no cost to the application.

GoRoutines are managed by the C language structure 'struct G'. Operating system threads are managed with the C language structure 'struct M'. Therefore, for every OS thread M, one or more G may run within it. There are other abstractions within the GoLang scheduler, but since those aren't relevant to this discussion we'll leave those abstractions alone for now.

All The G

Internally, GoRoutines are managed under the runtime package. There is a variable called runtime.allg which points to a list of all GoRoutines in the system. A corresponding length variable, runtime.allglen, defines how large this array is. As GoRoutines die, they are marked by their status as Dead. But, unless it is overwritten at some point, the pointer in allg lives on. So, you can inspect what's left of a GoRoutine even after it has moved on to its next iteration.

To solve our problem with GDB, we have to inspect the allg variable. As can be seen in the existing runtime-gdb.py code, this used to be as easy as calling gdb.parse_and_eval. Now that we can no longer act this easily, we have to use what resources are available to us to retrieve values from memory, even if it's a notorious pain in the ass.

Let's build a simple Python class around this idea. Because I solved my problem with this code last night in two hours while watching classic episodes of The Rockford Files, it isn't a super great solution. Regardless, it works and frankly because no one else has solved this problem for 2+ years, I don't care if you don't like it.

class Allg:
    __allglen = -1
    __position = 0
    __allg = 0

    __offsets = {
            'status': 152,
            'waitreason': 176,
            'goid': 160,
            'm': 200,
            'sched': 40,
            'sched.pc': 48,
            'sched.sp': 40,
            'stackguard': 120,
            'stackbase': 8,
        }

    def __init__(self):
        # first, fetch the number of active goroutines
        self.__allglen = int(gdb.parse_and_eval("&{uint64}'runtime.allglen'"))
        print("found allglen = {0}".format(self.__allglen))

        # get the next address in the array
        s = "&*{uint64}(&'runtime.allg')"
        self.__allg = int(gdb.parse_and_eval(s))
        print("found allg = {0}".format(hex(self.__allg)))

    def fetch(self):
        if self.__position >= self.__allglen:
            return None

        s = "&*{uint64}(" + "{0}+{1})".format(self.__allg, self.__position*8)
        p = int(gdb.parse_and_eval(s))
        self.__position += 1
        return p

    def Status(self, a):
        s = "&*{int16}(" + "{0}+{1})".format(a, self.__offsets['status'])
        return int(gdb.parse_and_eval(s))

    def WaitReason(self, a):
        s = "&*{int64}(" + "{0}+{1})".format(a, self.__offsets['waitreason'])
        x = int(gdb.parse_and_eval(s))
        s = "&{int8}" + "{0}".format(x)
        return str(gdb.parse_and_eval(s))

    def Goid(self, a):
        s = "&*{int64}(" + "{0}+{1})".format(a, self.__offsets['goid'])
        return int(gdb.parse_and_eval(s))

    def M(self, a):
        s = "&*{uint64}(" + "{0}+{1})".format(a, self.__offsets['m'])
        return int(gdb.parse_and_eval(s))

    def Pc(self, a):
        s = "&*{uint64}(" + "{0}+{1})".format(a, self.__offsets['sched.pc'])
        return int(gdb.parse_and_eval(s))

    def Sp(self, a):
        s = "&*{uint64}(" + "{0}+{1})".format(a, self.__offsets['sched.sp'])
        return int(gdb.parse_and_eval(s))

    def Stackguard(self, a):
        s = "&*{uint64}(" + "{0}+{1})".format(a, self.__offsets['stackguard'])
        return int(gdb.parse_and_eval(s))

    def Stackbase(self, a):
        s = "&*{uint64}(" + "{0}+{1})".format(a, self.__offsets['stackbase'])
        return int(gdb.parse_and_eval(s))

Using the class Allg, I simply identify the address of the runtime.allg symbol in memory, and its corresponding size parameter, runtime.allglen. Once I store these parameters internally, I can just fetch every subsequent GoRoutine's address from the array. Since these routines are allocated sequentially in the array, I can fetch them using a simple iterator. Then, I just pass back the pointer of the actual G* structure. Any time the caller wants to learn more about a specific G*, they just pass back the address to any other function in the class, which will return the value for the corresponding G* field. 

This simple class makes data retrieval very easy. Let's look back at the class that gets invoked when we execute info goroutines on the GDB command line. 

class GoroutinesCmd(gdb.Command):
    "List all goroutines."
    __allg = None

    def __init__(self):
        gdb.Command.__init__(self, "info goroutines", gdb.COMMAND_STACK, gdb.COMPLETE_NONE)

    def invoke(self, _arg, _from_tty):
        self.__allg = Allg()

        # donb: we can retrieve the correctly size pointer with a cast
        # (gdb) python \
        # print("{0}".format(gdb.parse_and_eval("&*{uint64}&'runtime.allg'")))
        while True:
            ptr = self.__allg.fetch()
            # print("fetched ptr = {0}".format(hex(ptr)))
            if not ptr:
                break

            st = self.__allg.Status(ptr)
            # print("status is {0}".format(st))
            w = self.__allg.WaitReason(ptr)
            # print("waitreason is {0}".format(w))
            #if st == 6:  # 'gdead'
                #print("skipping over dead goroutine")
                #continue

            s = ' '
            m = self.__allg.M(ptr)
            if m:
                s = '*'

            # if the status isn't "waiting" then the waitreason doesn' tmatter
            if st != 4:
                w = ''
            w2 = w.split('"')
            if len(w2) > 1:
                w = """waitreason="{0}\"""".format(w2[len(w2) - 2])

            pc = self.__allg.Pc(ptr)
            blk = gdb.block_for_pc(pc)
            goid = self.__allg.Goid(ptr)
            a = "fname={0} faddr={1}".format(blk.function, hex(pc))
            
            print(s, goid, "{0:8s}".format(sts[st]), a, "&g={0}".format(hex(ptr)), w)

How simple is that? Now, the routine can fetch each G* from within the invoke function's while loop, and print information regarding the runtime. 

donb@evian-les-bains:~/home/library/golang/go/src/pkg/regexp$ GOMAXPROCS=9 /usr/bin/gdb -q ./regexp.test
Reading symbols from ./regexp.test...done.
Loading Go Runtime support.
(gdb) run
Starting program: /home/donb/home/library/golang/go/src/pkg/regexp/regexp.test 
^C
Program received signal SIGINT, Interrupt.
runtime.usleep () at /home/donb/home/library/golang/go/src/pkg/runtime/sys_linux_amd64.s:77
77              RET
(gdb) info goroutines 
found allglen = 5
found allg = 0xc208018000
  16 waiting  fname=runtime.park faddr=0x4134d9 &g=0xc208002120 waitreason="chan receive"
* 17 syscall  fname=runtime.notetsleepg faddr=0x404a56 &g=0xc208002480 
  18 waiting  fname=runtime.park faddr=0x4134d9 &g=0xc208032240 waitreason="GC sweep wait"
  19 waiting  fname=runtime.park faddr=0x4134d9 &g=0xc2080325a0 waitreason="finalizer wait"
* 31 waiting  fname=runtime.gc faddr=0x40a0c6 &g=0xc2080326c0 waitreason="garbage collection"
(gdb) goroutine 31 bt
found allglen = 5
found allg = 0xc208018000
#0  0x000000000040a0c6 in runtime.gc () at /home/donb/home/library/golang/go/src/pkg/runtime/mgc0.c:2329
#1  0x000000000040a150 in runtime.gc () at /home/donb/home/library/golang/go/src/pkg/runtime/mgc0.c:2306
#2  0x00007fff00000000 in ?? ()
#3  0x000000c21531e000 in ?? ()
#4  0x000000000055fc00 in type.* ()
#5  0x0000000000000001 in ?? ()
#6  0x0000000000000000 in ?? ()
(gdb) 

We can even use the goroutine command using the same Python class to retrieve information about a specific GoRoutine, and then execute a gdb command based on that routine. Excellent!

Summary

This isn't a great way to debug GoLang. There is a lot that is left desired here. For example, stack backtraces are still difficult because of the execution architecture. GoLang's toolchain uses an internal Base Pointer (BP) and doesn't emit one when the binary is generated. This is a legacy of the Plan 9 Operating System assembler, which is intelligent on CISC ASM architectures such as x86/64 becuase it enables %R/BP to be used as a general register. 

But, as a result, GDB doesn't know how the heck to rewind the stack. In fact, you have to inspect the current function's SP adjustment code to identify how far to rewind the stack before popping off the return value. I've accomplished this (the basics) in another change I've made to the GDB script. But, I'll share that another time once I finish dealing with some of the gotchas of this method. 

Regardless, for now, you have a simple way to print each GoRoutine during a GDB session. You also have an easy way to identify where in memory each G* exists, and can inspect them with ease, and that's a lot better than you've had it for the past couple of years! 

GoLang Security Auditing 

Are you worried about the real internal security surface of the GoLang application architecture? Are you worried about how the subtleties of the custom scheduler can affect data consistency across co-routines? Are you wondering if the split-stack architecture puts you at risk for memory segement collision under significant client-request pressure? Are you concerned that poorly-written third party libraries might subvert the otherwise mostly-sound GoLang security model?

Come check out Lab Mouse Security! I've been working with GoLang since the project was made public. I understand the internal runtime architecture, the compiler toolchain, and how the security model affects real-world applications. If you're interested in GoLang security, consider having Lab Mouse evaluate the security of your GoLang application today! 

Best,
Don A. Bailey
Founder
Lab Mouse Security