Friday, December 12, 2014

Skipping a python unittest with a custom decorator

Example custom Python unittest skip decorator:

import functools
import glob
import os

def skipIfNoYamlFiles(f):
  @functools.wraps(f)
  def wrapper(*args, **kwargs):
    yaml_glob = os.path.normpath(os.path.dirname(__file__) + "/../../definitions/*.yaml")
    if glob.glob(yaml_glob):
      return f(*args, **kwargs)
    else:
      return unittest.skip("No YAML found with %s, skipping this test." % yaml_glob)
  return wrapper
Use it like this:
class MyTests(unittest.TestCase):

  @test_lib.skipIfNoYamlFiles
  def testValidation(self):
    """Ensure all Yaml validates."""
    print "test code goes here"

Wednesday, December 10, 2014

Migrating Chrome Profiles to per-channel directories

If you run custom chrome profiles you might see a message like this in the terminal if/when you launch chrome from the commandline:
[9894:9894:1210/140235:WARNING:sxs_linux.cc(139)] User data dir migration is only possible when the profile is used with the same channel.
It seems chrome recently made a change to where user profiles are stored. Previously different tracks (stable, beta etc.) all used the same profile like:
~/.config/google-chrome/myprofilename
Now however, these are split out by track like this:
~/.config/google-chrome/myprofilename
~/.config/google-chrome-beta/myprofilename
and if you run chrome beta with a profile that has also been used with chrome stable then chrome won't use it, and does a half-assed job of warning you about the problem (i.e. it prints a warning to the terminal as above, which you will only ever see if you're running it interactively). My reading of the bug was that this data wouldn't get migrated automatically, but you could migrate it yourself.

I did this for each profile and it seemed to work fine, all my settings and themes look correct:
cp -a ~/.config/google-chrome/myprofilename ~/.config/google-chrome-beta/

Friday, November 28, 2014

Make newly added files show up in git diff output

Sometimes it's handy to be able to show a normal diff for all the changes in a patch. The default behaviour is to hide the diffs of new files, i.e. in this case the output of "git diff" is missing the contents of newfile:
$ git init
Initialized empty Git repository in /gittemp/.git/
$ echo "blah" > newfile
$ git add newfile 
$ git diff
$ git status
# On branch master
#
# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached ..." to unstage)
#
# new file:   newfile
#
If you'd like to see the complete content of the new file in the diff output use the "-N" option to git add:
$ echo "blahmore" > newfile2
$ git add -N newfile2
$ git diff
diff --git a/newfile2 b/newfile2
index e69de29..39b5650 100644
--- a/newfile2
+++ b/newfile2
@@ -0,0 +1 @@
+blahmore

Sunday, November 23, 2014

Thunderbolt DMA attacks on OS X

The current TL;DR on Thunderbolt DMA attacks is that the VT-d IOMMU is doing its job and Ivy-Bridge (2012 and later hardware) Macs running OS X >= 10.8.2 are not vulnerable to the easy direct-write-to-memory-style attacks we saw popularized with firewire.

While Inception claims to work with Thunderbolt, it's really only a firewire attack, so you need a Thunderbolt to firewire converter and it's subject to the same limitations as normal firewire, as described at the end of this post.

There was a great 2013 Blackhat talk by Russ Sevinsky that covered lots of chip-level reverse engineering for Thunderbolt, but ultimately he didn't come up with an attack (excellent description of the reverse engineering process though). More recently snare described how to set up an attack on thunderbolt with an FPGA board connected to a mac via a Thunderbolt-PCIe device. But the IOMMU foiled his efforts on modern hardware. Snare says he's working on trying to bypass VT-d, so there may be interesting developments in the future.

For now you should probably still be more worried about snare's other work using PCIe option ROMs as a bootkit.

Sunday, November 9, 2014

SMTP email conversation threads with python: making gmail associate messages into a thread

I have some python software that sends emails, and I wanted gmail to group messages that were related to the same subject in a conversation. It's not immediately obvious how this works, and there's plenty of bad advice out there, including people stating that you just need to add "RE:" to the subject line, which is just wrong.

The way conversation threads are constructed is by using the SMTP "Message-ID" as a reference to the original email in the "In-Reply-To" and "References" headers. RFC2822 has the details, explains some fairly complex multi-parent cases, and includes some good examples. My use case was very simple, just two messages I wanted associated. The first message is sent with a message-id, the second one references it:
import email.utils
from email.mime.multipart import MIMEMultipart
import smtplib

myid = email.utils.make_msgid()
msg = MIMEMultipart("alternative")
msg["Subject"] = "test"
msg["From"] = "myuser@mycompany.com"
msg["To"] = "myuser@mycompany.com"
msg.add_header("Message-ID", myid)
s = smtplib.SMTP("smtp.mycompany.com")
s.sendmail("myuser@mycompany.com", ["myuser@mycompany.com"], msg.as_string())

msg = MIMEMultipart("alternative")
msg["Subject"] = "test"
msg["From"] = "myuser@mycompany.com"
msg["To"] = "myuser@mycompany.com"
msg.add_header("In-Reply-To", myid)
msg.add_header("References", myid)
s = smtplib.SMTP("smtp.mycompany.com")
s.sendmail("myuser@mycompany.com", ["myuser@mycompany.com"], msg.as_string())
Note that it is up to the host generating the message ID to guarantee it is unique. This function gives you an RFC-compliant message id and uses a datestamp to give you a unique ID. If you are sending lots of mail that may not be enough so you can pass it extra data that will get appended to the ID:
In [3]: import email.utils

In [4]: email.utils.make_msgid()
Out[4]: '<20141110055935.21441.10732@myhost.mycompany.com>'

In [5]: email.utils.make_msgid('extrarandomsauce')
Out[5]: '<20141110060140.21441.5878.extrarandomsauce@myhost.mycompany.com>'
I wasn't particularly careful with my first test message ID and sent a non-compliant one :) Gmail recognizes this and politely fixes it for you:
Message-ID: <545c12bc.240ada0a.6dba.5421SMTPIN_ADDED_BROKEN@gmr-mx.google.com>
X-Google-Original-Message-ID: testafasdfasdfasdfasdf

Wednesday, November 5, 2014

Splitting an array into fixed-size chunks with python

If you're looking for a way to split data into fixed size chunks with python you're likely to run across this recipe from the itertools documentation:
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
which certainly works, but why it works is less than obvious. In my case I was working with a small array where the data length was guaranteed to be a multiple of 4. I ended up using this, which is less sexy but more comprehendable:
[myarray[i:i+4] for i in xrange(0, len(myarray), 4)]

Monday, October 27, 2014

Authenticode signing windows executables on linux

We had a particularly painful build and sign workflow that required multiple trips between linux and windows.  I looked around and found the following options for signing windows binaries on linux:
  • jsign, a java implementation
  • signcode from the Mono project, as suggested by Mozilla.  It's in the mono-devel ubuntu package.
  • osslsigncode, an Openssl-based implementation of authenticode signing that uses curl to make the timestamp requests.
The Mozilla instructions are good for getting your keys and certs into a format that will work with these tools. Some minor additions to those below:

openssl pkcs12 -in authenticode.pfx -nocerts -nodes -out key.pem
openssl rsa -in key.pem -outform PVK -pvk-strong -out authenticode.pvk
openssl pkcs12 -in authenticode.pfx -nokeys -nodes -out cert.pem
cat Thawte_Primary_Root_CA_Cross.cer >> cert.pem
openssl crl2pkcs7 -nocrl -certfile cert.pem -outform DER -out authenticode.spc
shred -u key.pem
Once you're done here you have authenticode.pvk with your encrypted private key, and authenticode.spc with your public certs. Appending the cross cert is necessary to make signature validation work with some tools. The windows GUI "Properties|Digital Signatures|Details" dialog will tell you "This digital signature is OK" but if you check with signtool verify on Windows, you'll find it isn't:
>"C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\signtool.exe" verify /v /kp my.exe

Verifying: my.exe

[snip]

SignTool Error: Signing Cert does not chain to a Microsoft Root Cert.

Number of files successfully Verified: 0
Number of warnings: 0
Number of errors: 1
I suspect the GUI uses the local cert store and/or APIs that automatically fetch the required cross cert, but signtool and 3rd-party signature verifiers do not. With the cross cert added to the spc as above it can be correctly verified and mentions the MS cross cert:
Z:\signing\windows>"C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\signtool.exe" verify /v /kp my.exe

Verifying: my.exe

[snip]

Cross Certificate Chain:
    Issued to: Microsoft Code Verification Root

[snip]

Successfully verified: my.exe
If you use Bit9 it's also worth checking that it will verify your binary using the dascli.exe tool:
>"C:\Program Files (x86)\Bit9\Parity Agent\DasCLI.exe" certinfo my.exe
File[C:my.exe]
Elapsed[630ms]
CertValidated[Y] Detached[N] Publisher[My Inc]
FileVerified[Y]

[snip]
So, back to signing on Linux. At first I tried installing mono and using "signcode". It claims to succeed:
$ signcode sign -spc authenticode.spc -v authenticode.pvk -a sha1 -$ commercial -n MyApp -t http://timestamp.verisign.com/scripts/timestamp.dll -tr 5 my.exe
Mono SignCode - version 3.2.8.0
Sign assemblies and PE files using Authenticode(tm).
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

Enter password for authenticode.pvk: 
MY_GODDAM_PASSWORD_IN_CLEARTEXT
Success
And in the process echoes your password in cleartext!?! This is something I was prepared to fix with a "read -s -p 'Password'" wrapper script like this guy, but the signature was no good. I could see it appended in a hexeditor but Windows didn't give me a Digital Signature tab in the GUI and signtool couldn't find it either:
>"C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\signtool.exe" verify /v /kp my.exe

Verifying: my.exe
SignTool Error: No signature found.

Number of files successfully Verified: 0
Number of warnings: 0
Number of errors: 1
It's possible that there's something weird about our exe that caused this to fail. Someone else reported a similar problem but then later claimed it was due to a corrupted exe. In any case, not being particularly wedded to, or happy with, mono and signcode at this point I tried osslsigncode, which worked fine and produced a valid signature.
sudo apt-get install libcurl4-openssl-dev
./configure
make
sudo make install
osslsigncode sign -certs authenticode.spc -key authenticode.pvk -n "MyApp" -t http://timestamp.verisign.com/scripts/timstamp.dll -in my.exe -out my_signed.exe
Update: After coming across this mozilla post, I suspect my problem with mono's signcode was that signcode may not support 64 bit, but I didn't go back to check.