tags:

views:

56

answers:

1

Hi,

Does it happen that some program (or even the OS itself) changes the contents of an executable's __TEXT segment, for whatever reason?

  • Note: Here, I'm referring to the "__TEXT" segment, not the "__text" section.

In other words: can I rely on bytes in the __TEXT segment of my executable to detect whether my executable has been damaged (say by computing a checksum on that segment), or is there a chance I get false positives because this segment may be modified after the program has been installed on the user's computer?

Thanks!

+3  A: 

Segments are essentially a virtual memory construct: they're typically aligned on page boundaries, so they may end up including a bit more than your application's code. Given the __TEXT segment usually starts at the beginning of a Mach-O file, this generally includes the Mach-O headers, too.

In OS X 10.3 and earlier, prebinding could affect the __TEXT segment (which is described in detail here). In later versions, code signing can also modify the __TEXT segment.

You may want to investigate using OS X's built-in code-signing mechanism (the cause of, and solution to, your problem?). Some recommended references:

You may find macholib useful in exploring. (It's included with recent OS X versions to support py2app.) Here's a simple script I used to extract a __TEXT segment.

from macholib.MachO import MachO

m = MachO('foo')
__TEXT = (cmd for load_cmd, cmd, data in m.headers[0].commands
          if getattr(cmd, 'segname', '').rstrip('\0') == '__TEXT').next()
print '__TEXT segment: offset %x size %x' % (__TEXT.fileoff, __TEXT.filesize)
f = open('foo', 'rb')
f.seek(__TEXT.fileoff)

open('foo__TEXT', 'wb').write(f.read(__TEXT.filesize))

Of course, you can also use otool -lv, but the output is a bit messy and hard to parse.

Nicholas Riley
Thanks Nicholas, that's a really documented answer! I'll investigate all this as soon as I get back to work.
Carl Seleborg
Yep, turns out code signing, basically happens every time you download an application and click "Authorize" on the pop-up asking you whether running this is safe, is a common cause of __TEXT changing.
Carl Seleborg