Image of the glider from the Game of Life by John Conway
Skip to content

Rejected And Legal

Some of the roles I fill at work are: storage architecture, cloud engineering, system administration and backend coding. When approaching my tasks head on, it’s always important to me that standards are adhered to. From PEP coding style to adhering to an RFC for mail server. Unfortunately, I think I’m a dying breed, or something, because more and more, I’m seeing standards ignored.

Case in point: I just filled out a form for a survey to “enter to win a $1000 shopping spree). You know, the crap that you constantly get bombarded with at the checkout stand when the cashier gives you your receipt. I always ignore them, but then thought to myself “I’ll never win if I don’t at least try”, so I gave my first survey a go. At the end of the survey, it asked for my email address. I figure they’ll sell it for marketing purposes, and I have a Google Mail address, so I’m not really that worried about the SPAM (their SPAM filters are amazing). But, I would like to track who they are selling my address to. So, I gave them the following address:

aaron.toponce+survey-provider@gmail.com

To which, I received an error that the email address is not a valid address. AHEM! Yes it is, and it’s this lack of support for standards that I’m talking about. My email address was rejected, yet it’s perfectly legal according to RFC 5322. You see, according to that RFC, I get the following flexibilities with my email address:

  • ASCII upper and lower case letters (a-z & A-Z).
  • ASCII digits 0-9
  • ASCII characters !#$%&’*+-/=?^_`{|}~
  • ASCII dot (.) so long as the local part of the address does not contain the dot consecutively, and it does not start with a dot.
  • ASCII characters ” ” (space) and “(),:;<>@[\] are allowed with certain restrictions.

So, I could have the following email addresses, all of which are perfectly legit according to the RFC:

  • “[Aaron Toponce]“@gmail.com
  • a&t@gmail.com
  • aaron.toponce+business@gmail.com
  • aaron’s-travel-agency@example.travel
  • {atoponce}@gmail.com

Yet, these will get ejected outright in most web forms I’ve come across. Specifically interesting is the .travel TLD. I’ve had web forms enforce TLDs that are less than 4 characters, which is absolutely absurd for the .travel and .museum TLDs. I’m guessing one of two things is happening with these web forms:

  1. The developer used the regular expression [A-Za-z0-9_\-\.]+@[A-Za-z0-9\-\.]+ for validating addresses.
  2. There is absolute denial for the use of “plus-addressing” as a DEA.

I’m guessing the first is more likely the scenario than the second. Regardless, Of course, when we’re talking about the rules of RFC 5322, we’re no longer talking about regular expression syntax. We’re talking about grammar. If your page is designed in PHP, Python, CGI, or whatever, you should use a real parser for parsing the email address, rather than reinventing the wheel yourself. What’s unfortunate, is this disease of not properly parsing valid email addresses is found in some big companies and sites too, not just the little guys.

Now, Google COULD provide true DEAs, such as Yahoo! Plus does with their subscribers, However, I should be able to create an DEA with an already existing email address, rather than creating completely new ones, because people refuse to conform to the standards. So Google, if you’re reading (I know you are), you may want to consider proper DEAs, seeing as though “plus addressing” isn’t working, and it is important to some.

Stéphane Bortzmeyer has already blogged about this, and he uses the #ral hashtag on Identica and Twitter to vent his frustrations, which stands for “Refus d’Adresses Légales” or “Rejection of Legal Address”. Well, I’ve determined that I will be doing the same, although I’ll bacronym the hashtag to “Rejected And Legal”, along with the url to the site that refuses to adhere to the RFC.

Use wget(1) To Expand Shortened URLs

I’m a fan of all things microblogging, but let’s face it: until URLs become part of the XML, and not part of your character count (which is ridiculous anyway), shortened URLs are going to be a way of life. Unfortunately, those shortened URLs can be problematic. They could host malicious scripts and/or software that could infect your browser and/or system. They could lead you to an inappropriate site, or just something you don’t want to see. And because these URLs are a part of our microblogging lives, they’ve also become a part of our email, SMS, IM, IRC, lives as well as other online aspects.

So, the question is: do you trust the short URL? Well, I’ve generally gotten into the habit of asking people to expand the shortened url for me if on IRC, email or IM, and it’s worked just fine. But, I got curious if there was a way to do it automagically, and thankfully, you can use wget(1) for this very purpose. Here’s a “quick and dirty” approach to expanding shortened URLs (emphasis mine):

$ wget --max-redirect=0 -O - http://t.co/LDWqmtDM
--2011-10-18 07:59:53--  http://t.co/LDWqmtDM
Resolving t.co (t.co)... 199.59.148.12
Connecting to t.co (t.co)|199.59.148.12|:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: http://is.gd/jAdSZ3 [following]
0 redirections exceeded.

So, in this case “http://t.co/LDWqmtDM” is pointing to “http://is.gd/jAdSZ3″, another shortened URL (thank you Twitter for shortening what is already short (other services are doing this too, and it’s annoying- I’m looking at you StatusNet)). So, let’s increase our “–max-redirect” (again, emphasis mine):

$ wget --max-redirect=1 -O - http://t.co/LDWqmtDM
--2011-10-18 08:02:12--  http://t.co/LDWqmtDM
Resolving t.co (t.co)... 199.59.148.12
Connecting to t.co (t.co)|199.59.148.12|:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: http://is.gd/jAdSZ3 [following]
--2011-10-18 08:02:13--  http://is.gd/jAdSZ3
Resolving is.gd (is.gd)... 89.200.143.50
Connecting to is.gd (is.gd)|89.200.143.50|:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: https://wiki.ubuntu.com/UbuntuOpenWeek [following]
1 redirections exceeded.

So, in this case, the link finally points to https://wiki.ubuntu.com/UbuntuOpenWeek. I’m familiar enough with the Ubuntu Wiki, that I know I should be safe visiting the initial shortened URL. If you want to add this to a script or shell function, then you can get a bit more fancy:

$ expandurl() { wget -O - --max-redirect=$2 $1 2>&1 | grep ^Location; }
$ expandurl http://t.co/LDWqmtDM 1
Location: http://is.gd/jAdSZ3 [following]
Location: https://wiki.ubuntu.com/UbuntuOpenWeek [following]

In this case, our “expandurl()” function takes two arguments: the first being the URL you wish to expand, and the second being the max redirects. You’ll notice further that I added “-0 -” to print to STDERR. This is just in case you give too many redirects, it will print the content of the page’s HTML to the terminal, rather than saving to a file. Because you’re grepping for “^Location”, and sending the HTML to your terminal anyway, technically you could get rid of the “–max-redirects” altogether. But, keeping it in play does seriously increase the time it takes to get the locations. Whatever works for you.

UPDATE (Oct 18, 2011): After some comments have come in on the post, and some discussion on IRC, there is a better way to handle this. According to the wget(1) manpage, “-S” or “–server-response” will print the headers and responses printed by the FTP/HTTP servers. So, here’s the updated function that you might find to be less chatty, and faster to execute as well:

$ expandurl() { wget -S $1 2>&1 | grep ^Location; }
$ expandurl http://t.co/LDWqmtDM
Location: http://is.gd/jAdSZ3 [following]
Location: https://wiki.ubuntu.com/UbuntuOpenWeek [following]

Perfect.

Why Firefox Is My Browser Of Choice

Posted to my Google Plus account (https://plus.google.com/115784859563110525602/posts/cwwMBdh4iPL):

Let’s talk browsers. Specifically, Opera 11.51, Firefox 7.0.1, Safari 5.1 and Chrome 14.0.835.163. I don’t have access to Internet Explorer 9. Ordered best to worst.

JavaScript standards compliance: http://test262.ecmascript.org (lower failures is better):
Firefox: 191 failures
Chrome: 425 failures
Safari: 832 failures
Opera: 3,750 failures

HTML5 standards compliance: http://html5test.com (higher is better):
Firefox: 313 and 9 bonus points
Safari: 293 and 8 bonus points
Opera: 286 with 7 bonus points
Chrome: 284 and 2 bonus points

CSS3 standards compliance: http://acid3.acidtests.org (higher is better):
All score 100% with fluid animation.

JavaScript benchmark performance: http://webkit.org/perf/sunspider/sunspider.html (lower is better):
Firefox: 211.9ms +/- 1.3%
Opera: 258.2ms +/- 2.7%
Safari: 291.4ms +/- 0.9%
Chrome: 298.3ms +/- 7.1%

In every test, Firefox 7 came out on top. I realize it’s the newest browser of the bunch, but it’s fairly clear that it’s holding its own against its competitors. It performs, it’s standards compliant, and it’s still my browser of choice. Further, it’s interesting that Firefox beats the pants out of Chrome in 3 of the 4 tests, and yet Chrome is gaining market share. Go figure.

Salt Packaged For Debian/Ubuntu

I created a Debian package for Salt, doing my best to adhere to the Debian Policy. You can find it at http://mentors.debian.net/package/salt. If you’re not familiar with Salt, head over to http://saltstack.org and check it out. From the author’s website:

Salt is a powerful remote execution manager that can be used to administer servers in a fast and efficient way.

Salt allows commands to be executed across large groups of servers. This means systems can be easily managed, but data can also be easily gathered. Quick introspection into running systems becomes a reality.

Remote execution is usually used to set up a certain state on a remote system. Salt addresses this problem as well, the salt state system uses salt state files to define the state a server needs to be in.

Between the remote execution system, and state management Salt addresses the backbone of cloud and data center management.

Think Puppet on steroids. And done correctly.

At any event, yes, I’m looking for a Debian Developer to sponsor me getting it into Debian proper. If you are an Ubuntu Developer, and could help sponsor me getting it into Ubuntu as well, that would be awesome!

How To Properly Create And Burn CD/DVD ISO Images From The Command Line

Too often, I see the recommendation on forums, IRC, and elsewhere across the internet to use improper tools for creating ISO images. For example, consider the following two commands, both of which are not the correct way to build a CD/DVD image:

$ dd if=/dev/scd0 of=cdimage.iso # NO!

Or worse yet:

$ cat /dev/scd0 > cdimage.iso # NO!

As you are probably thinking, the problem with the two commands above, is that they provide no error checking while building the image. So, in order to make sure you have all the bits, you need to use another tool, such as using the MD5 hashing algorithm:

$ md5sum /dev/scd0 cdimage.iso
d642d524dd2187834a418710001bbf82  /dev/cdrom
d642d524dd2187834a418710001bbf82  cdimage.iso

Thankfully, the hashes above match. But, what if they didn’t? Then, you get to redo your dd(1) command (or, shudder, cat(1)) from above, and then rerun md5sum(1) to make sure you got all the bits. Doesn’t sound like much fun to me. Thankfully, there is a better way, one which handles the checksum while doing the copy.

You want to use readom(1) (“read optical media”) from the wodim(1) (“write optical disk media”) package. Consider the following command:

$ readom dev=/dev/scd0 f=cdimage.iso # YES!

If readom(1) fails to get the bits during the copy, it will let you know that it’s struggling. If it got all the bits, you know you have them all, because of the error checking during the copy. Sure will save you a lot of time running manual hashes when finished.

Now, what about burning a copy of the ISO image? Surely you use dd(1), yes? Something like:

$ dd if=cdimage.iso of=/dev/scd0 # NO!

NO! Instead, use wodim(1) directly:

$ wodim -v -eject cdimage.iso # YES!

For the same reasons that you want to use readom(1) for creating ISO images from CD/DVD, you want to use wodim(1) for burning ISO images to CD/DVD. What happens if after using dd(1) to create your CD/DVD, the md5sum(1) hash doesn’t line up with the image? You didn’t get all the bits, and created a coaster. Use wodim(1) and should it succeed, you can rest assured that you have all the bits.

So, remember, readom(1) and wodim(1) are the tools you want when creating and/or burning ISO images from the command line. Any other tool, and you’re likely doing it wrong.

Avoid Using which(1)

This post comes from BashFAQ/081 on Greg’s Wiki. He argues why you should not be using which(1) to determine if a command is in your $PATH at the end of the page. I’ll put that argument at the front:

The command which(1) (which is often a csh script, although sometimes a compiled binary) is not reliable for this purpose. which(1) may not set a useful exit code, and it may not even write errors to stderr. Therefore, in order to have a prayer of successfully using it, one must parse its output (wherever that output may be written).

Note that which(1)’s output when a command is not found is not consistent across platforms. On HP-UX 10.20, for example, it prints “no qwerty in /path /path /path …”; on OpenBSD 4.1, it prints “qwerty: Command not found.”; on Debian (3.1 through 5.0 at least) and SuSE, it prints nothing at all; on Red Hat 5.2, it prints “which: no qwerty in (/path:/path:…)”; on Red Hat 6.2, it writes the same message, but on standard error instead of standard output; and on Gentoo, it writes something on stderr.

(Quotation and manpage reference additions mine). So, if which(1) is bad news, then what is the “proper” way to determine if a command is in your $PATH? Well POSIX has an answer, and not surprisingly, the command to use is “command”:

1
2
3
4
5
6
# POSIX
if command -v qwerty >/dev/null; then
  echo qwerty exists
else
  echo qwerty does not exist
fi

The “command” built-in also returns true for shell built-ins. If you absolutely must check only PATH, the only POSIX way is to iterate over it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# POSIX
IsInPath ()
(
  [ $# -eq 1 ] && [ "$1" ] || return 2
  set -f; IFS=:
  for dir in $PATH; do
    [ -z "$dir" ] && dir=. # Legacy behaviour
    [ -x "$dir/$1" ] && return
  done
  return 1
)

if IsInPath qwerty; then
  echo qwerty exists
else
  echo qwerty does not exist
fi

There are also Bash built-ins that can be used, should you have Bash installed on your system:

1
2
3
4
5
6
# Bash using the 'hash' built-in
if hash qwerty 2>/dev/null; then
  echo qwerty exists
else
  echo qwerty does not exist
fi

Or:

1
2
3
4
5
6
7
# Bash using the 'type' built-in
# type -P forces a PATH search, skipping builtins and so on
if type -P qwerty >/dev/null; then
  echo qwerty exists
else
  echo qwerty does not exist
fi

If you prefer the ZSH (my addition not present in the wiki), as I do, then you can look in the $commands associative array:

1
2
3
4
5
6
# ZSH using the $commands associative array
if [[ $commands[qwerty] >/dev/null ]]; then
    echo qwerty exists
else
    echo qwerty does not exist
fi

I like that at the end of the FAQ, he gives a shell script for using which(1) should it be absolutely necessary. Not only do you have to test for exit code, but you also have to test for common strings in the output, seeing as though which(1) doesn’t always use exit codes properly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Bourne.  Last resort -- using which(1)
tmpval=`LC_ALL=C which qwerty 2>&1`
if test $rc -ne 0; then
  # FOR NOW, we'll assume that if this machine's which(1) sets a nonzero
  # exit status, that it actually failed.  I've yet to see any case where
  # which(1) sets an erroneous failure -- just erroneous "successes".
  echo "qwerty is not installed.  Please install it."

else
    # which returned 0, but that doesn't mean it succeeded.  Look for known error strings.
    case "$tmpval" in
      *no\ *\ in\ *|*not\ found*|'')
        echo "qwerty is not installed.  Please install it."
        ;;
      *)
        echo "Congratulations -- it seems you have qwerty (in $tmpval)."
        ;;
    esac
fi

CONCLUSION:
You have many options to find whether or not a command exists in your $PATH, some POSIX, some proper built-ins. Regardless, you should be able to build platform-independent scripts using the proper tools, and using which(1) is not the right tool for the job. Hopefully, this has convinced you of that.

Alphabet Book

image

Our family has been tasked with drawing a picture for each letter of the alphabet in an alphabet book for my soon-to-be-born niece. The letter ‘d’ was available, so it was obvious to me what should be drawn. I know when she starts flipping through the pages of the book, she will love this page the best.

PGP/MIME Versus S/MIME

I’m going to try to keep this post short (many of my regular readers will know how long winded I can be). However, with my recent post of setting up Mutt to support both PGP/MIME and S/MIME, based on the account I’m using, I figure a followup post on their similarities and differences might be in order. So, here it goes:

PGP/MIME

  1. Uses the OpenPGP RFCs and standards.
  2. The “signature.asc” detached signature is in plain text.
  3. Flexibility in algorithm choice for encryption, signing and compression.
  4. Relies on a distributed trust model.
  5. Not as widely deployed in MUAs as S/MIME.
  6. Public key must be distributed separately from the signature.
  7. Trivial to integrate with webmail providers.
  8. Can only be used with signing documents.
  9. An expiration date does not need to be set on the public key.
  10. Free.

S/MIME

  1. Based on a number of RFCs and standards.
  2. The “smime.p7s” detached signature is in a binary format.
  3. Generally, the Certificate Authority (CA) chooses the algorithm and key size.
  4. Relies on a centralized trust model.
  5. More widely deployed than PGP/MIME
  6. Public certificate distributed in each detached signature.
  7. Difficult to integrate with webmail providers.
  8. Can be used for both signatures and encryption.
  9. Generally, the public certificate expires once per year.
  10. Some CAs provide certs free for personal use, but most if not all CAs charge for professional use. As low as $20 per year, depending on the CA.

This isn’t an exhaustive list, but it’s pretty good. I’ve tried to keep any bias out of the list, and just mention the facts. Really, I get a kick out of using both, so meh. But, if I were forced to choose, I would choose the distributed OpenPGP model for signatures.

The biggest reason for this choice actually doesn’t even use PGP/MIME, thus the reason it’s not listed. That reason is I can set preferences in my key as to what must be used when encrypting documents to me. Thus, I can force you to send me a 2048 RSA encrypted document. With S/MIME, which can handle encryption, no such preferences exist, which means that there is nothing from stopping you sending me a 40-bit RSA encrypted document. I think you can see the security problem here.

Another problem I see with S/MIME is the reliance on a centralized authority. Essentially, you can trust I signed my mail with S/MIME, because my certificate is signed by DigiNotar and we all trust DigiNotar. Oh, wait. While the issuance of fraudulent public keys is a reality, the probability is much less likely, due to the distributed Web of Trust. Of course, this means there is a fair amount of homework that you must do in verifying that the key is legit, and that confidential information can be trusted with that key, but it is possible to make such assumptions.

Lastly, S/MIME is rather trivial to maintain. You pay a CA for a certificate, and you install the certificate in your mail client, and you’re ready to go. OpenPGP and PGP/MIME isn’t so trivial. You must generate your own keys, generally with PGP or GnuPG, and know the difference between your private and public keys. Then, you must install a plugin or extension into your MUA, which all don’t support, and configure that plugin to work with your keys. Then you must distribute your public key to friends and family, as well as keyservers, so others can grab a copy. But they can’t trust your data, until they meet up with you and do a keysigning, which means you must then redistribute the public key after their signature has been applied. In both cases, however, you can’t encrypt data to people unless you have their public key or certificate.

Both are internet standards, and both are fairly widely deployed. Unfortunately, there is work on your end that must be done on setting it up, and maintaining it, whether it’s a yearly cost or attending keysigning parties. As a result, it’s not as widely used in practice as much as it could be. I’ve made it a personal philosophy that I won’t send mail unless it’s cryptographically signed. This is true both personally and professionally. I would love it if my family and friends took the steps necessary to verify the signature, but it just isn’t going to happen. End-to-end security with email seems to have just too many speed bumps that people are willing to handle. That won’t stop me though.

Anyway, I hope this was at least somewhat informative.

Setting Up Mutt With S/MIME And PGP/MIME

If you have two accounts that you use with Mutt, and one of them you would like to use your OpenPGP key for signing mail (PGP/MIME), and the other you would like to use an OpenSSL certificate for doing the same (S/MIME), then this post is for you. Before beginning, however, you need to have the development version of Mutt (1.5.x) and it needs to have S/MIME support compiled in (which is the default for Debian/Ubuntu).

In my “~/.muttrc”, I have my accounts separated into two files, so I can set specific options for each account that don’t affect the other. As a result, here is the relevant parts of my ~/.muttrc:

# ~/.muttrc
folder-hook "personal.mail.tld" "source ~/.mutt/personal.rc"
folder-hook "work.mail.tld" "source ~/.mutt/work.rc"
source ~/.mutt/personal.rc # use this as the default account when Mutt executes

So, I have two accounts: “personal.mail.tld” and “work.mail.tld” (those are actual URLs to your accounts, whether they be GMail, Yahoo!, or whatever. Change as necessary). So, let’s take a loot at the relevant parts of “~/.mutt/personal.rc” and “~/.mutt/work.rc”:

# ~/.mutt/personal.rc
source ~/.mutt/gpg.rc
# ~/.mutt/work.rc
source ~/.mutt/smime.rc

Obviously, I’m sourcing external files. The personal account sources the gpg.rc config, while the work account sources the smime.rc config. Both of these configs can be found as example files in “/etc/Muttrc.d/” on Debian. From there, I made my edits.

Obviously, for both configs, I will have needed to setup cryptographic keys. For GnuPG, I will need to generate and save off my public key pair. There is a wealth of documentation on the internet that discusses this, so I won’t cover that here. I’ll just assume you have it created already.

For S/MIME, you will need to generate an OpenSSL certificate, signed by a centralized certificate authority. For myself, I chose Comodo. It was easy and quick. I had my SSL cert in less than 5 minutes, and it’s good for a full year, and it was free.

Once you get the email about the certificate, when you click the link to open it in your browser, it will install your certificate in the browser. No big deal. Just navigate to the certificate using your browser’s menu, and backup the certificate (both the private and public keys) to some local directory on your machine. It should have “.p12″ as its extension. Then, copy the certificate to the machine that will be running Mutt.

On the machine that you will be running Mutt from, you will need to issue a few commands to get your environment setup correctly before you can start using the certificate. You will need OpenSSL installed before you can begin:

$ smime_keys init

This should create “~/.smime/”, “~/.smime/certificates/” and “~/.smime/keys/”. After which, you will need to copy “ca-bundle.crt” to “~/.smime/”. “ca-bundle.crt” is provided by a number of packages, and you can find it on the internet should it not already be installed. After that is copied, type the following:

$ smime_keys add_p12 /path/to/your-backed-up-cert.p12

You will be asked for the passphrase for the private key in the .p12 file, as well as a new passphrase for encrypting the key in your database. It doesn’t matter if you use the same passphrase both times. This passphrase is not recoverable, so make sure you remember it. You will also be asked what you want to call the certificate; it makes no difference to anyone what you call it, but you can’t have two certificates with the same nickname.

Make note of the hash of your key. You can retrieve this hash from the line “added private key” followed by a path and a hexadecimal number ending in “.0″. Find the line in your .muttrc that says:

# ~/.mutt/smime.rc
set smime_default_key="12345678.0"

and change “12345678.0″ to the hash for your key that you took note of. The only thing left to do is to install the Comodo root certificates. These are already installed on your system in “/etc/ssl/certs/Comodo*” and “/etc/ssl/certs/COMODO*”. For each of those root certs (I’m actually not sure which is needed for your personal cert), you need to issue the following command:

$ smime_keys add_root /etc/ssl/certs/Comodo_Secure_Services_root.pem

You have now successfully setup your environment to use S/MIME with Mutt. Now let’s look at the configs. For the gpg.rc config, I kept everything default except for the following:

# ~/.mutt/gpg.rc
set pgp_good_sign="^gpg: Good signature from"
set crypt_autosign="yes"
set crypt_replysign="yes"
set crypt_replysignencrypted="yes"
set pgp_auto_decode="yes"
unset smime_is_default

For the smime.rc config, again I kept everything default except for the following:

# ~/.mutt/smime.rc
set smime_is_default="yes"
set crypt_autosmime="yes"
set pgp_autosign="no"
set smime_timeout="300"
set crypt_autosign="yes"
set crypt_replyencrypt="yes"
set crypt_replysign="yes"
set crypt_replysignencrypted="yes"
set crypt_verify_sig="yes"
set smime_default_key="12345678.0" # you should have already changed this

You are now ready to roll. When you change to your personal account, it should use PGP/MIME by default, and when you change to your work account, it should use S/MIME by default.

Use Your SSH Client To Help Prevent Stupid Mistakes

I have chosen the path of system administration for my career. It’s been very rewarding, and I really love my job. However, there are times when I make stupid mistakes that cost others money. I’m sure we’ve all been there. It’s stressful, embarrassing and can really shake you up, if you mistake is bad enough. Many times, this happens because you fat-fingered an IP address, hostname, or something else, and your SSH client takes you somewhere you shouldn’t be. If that’s the case, hopefully this post can help.

According to the ssh_config(5) manual:

     LocalCommand
             Specifies a command to execute on the local machine after suc‐
             cessfully connecting to the server.  The command string extends
             to the end of the line, and is executed with the user's shell.
             The following escape character substitutions will be performed:
             ‘%d’ (local user's home directory), ‘%h’ (remote host name), ‘%l’
             (local host name), ‘%n’ (host name as provided on the command
             line), ‘%p’ (remote port), ‘%r’ (remote user name) or ‘%u’ (local
             user name).

             The command is run synchronously and does not have access to the
             session of the ssh(1) that spawned it.  It should not be used for
             interactive commands.

             This directive is ignored unless PermitLocalCommand has been
             enabled.

As mentioned, the used of LocalCommand executes a local command after successfully connecting to the server. I figured this would be a great way to print something to the terminal, letting me know whether or not my client just connected to a production machine, a QA machine, or a development machine.

I wanted to use colors, to make it obvious. I don’t want to make the same mistake twice, so I want it painfully clear what machine I just went to. As a result, if I go to a development or home machine, use green. If I enter a QA machine, use yellow. If I enter a production, or other serious machine I probably shouldn’t be on, use red. As a result, I can take advantage of the ANSI escape sequences for color. In case you forgot, here are the colors and modes:

Colors
\e[{attr1;…;{attrN}m

Text attributes
0 Reset
1 Bright
2 Dim
4 Underscore
5 Blink
7 Reverse
8 Hidden

Foreground Colors
30 Black
31 Red
32 Green
33 Yellow
34 Blue
35 Magenta
36 Cyan
37 White

Background Colors
40 Black
41 Red
42 Green
43 Yellow
44 Blue
45 Magenta
46 Cyan
47 White

So, if I were about to SSH to a production machine, I probably want to make it as obvious as possible. Thus, I could print to the terminal, in blinking, bold, red text “PRODUCTION”. I could use the following command:

print "\e[1;5;31PRODUCTIONm\e[0;m"

Notice that at the end of the sequence, I’m resetting the text attributes. This is because if you don’t do this, you will keep the text attributes in your terminal, and that may have an affect on how the text is displayed when in your remote SSH connection.

A possible ~/.ssh/config file could look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Host development
    Hostname dev.domain.tld
    LocalCommand print "\e[1;32mDevelopment\e[0;m"
    PermitLocalCommand yes

Host qa
    Hostname qa.domain.tld
    LocalCommand print "\e[1;33mQuality Assurance\e[0;m"
    PermitLocalCommand yes

Host production
    Hostname prod.domain.tld
    LocalCommand print "\e[1;5;32mPRODUCTION\e[0;m"
    PermitLocalCommand yes

Here is a screenshot in action (without the blink):

My Tmux Hardstatus Theme

Recently, I’ve made the switch from GNU Screen to Tmux for my remote terminal multiplexor. I still prefer GNU Screen for serial connections, however (something the Tmux developers don’t seem to think is important). So, when getting it setup, I wanted my hardstatus line to imitate my GNU Screen hardstatus line as closely as possible. Well, I got it to that point, then took it even further to work with my custom Irssi and ZSH themes (I want everything to tie in nicely). The only thing left is getting Mutt in order, but that’s for another post.

At any event, here is the configuration for the theme:

1
2
3
4
5
6
7
8
9
10
11
12
# hardstatus line theme
set-option -g status-fg white
set-option -g status-bg default
set-option -g status-justify centre
set-option -g status-left-length 13
set-option -g status-left '#[fg=green][ #[fg=black,bright]#h #[fg=green,nobright]][#[default]'
set-option -g status-right-length 16
set-option -g status-right '#[fg=green]][ #[fg=black,bright]%m/%d %H:%M #[fg=green,nobright]]#[fg=default]'
set-window-option -g window-status-current-format '#[fg=red,bg=default]( #[fg=white,bright,bg=default]#I:#W#[fg=red,nobright,bg=default] )#[fg=default]'
set-window-option -g window-status-alert-attr bold
set-window-option -g window-status-alert-fg yellow
set-window-option -g window-status-alert-bg default

Obviously, this won’t look that great on a terminal with a white background (or really any color other than black). And here is the screenshot:

As you can clearly see, the active window you’re under is bold white with red parentheses around the window name. The previous window you were in is marked with a dash ‘-’ (by default). An alert in a terminal will change the text to bold yellow, so long as you’re not in that window (as you can see with the “mutt” window). It ties in nicely with the 88_madcows.theme file for Irssi, and the ZSH theme I built.

I’m new to building Tmux hardstatus lines, so if there is something I should be doing differently, let me know.

I Am Going To OLF

I will be attending the Ohio Linux Fest this September (in about two weeks) giving a talk on “Password Theory and Breaking Encrypted Filesystems”. The talk covers some theory on what exactly makes a “secure password”, including some mathematics, entropy, random number generators, shadowed passwords, salts, rainbow tables and cryptographic hashes. I end the talk by showing how to break into an encrypted filesystem, regardless of the type of encryption, or the software used to encrypt the filesystem. It should be a good talk. When my slides are ready, I’ll make them available online.

If you have thought about attending, you should register. You can see my talk, if you sign up just for the enthusiast package. You can attend a sponsored lunch (and other things) if you upgrade.

Also, I’ll be hosting the PGP keysigning party at the conference as well (a follow-up post is coming). My key is in the “strong set”, so by me signing your key, I’ll also be bringing you into the strong set as well, if you’re currently not in it. It’s all about strengthening the Web of Trust.

At any event, see you at the fest!

Pimp My Irssi – Part 2

It’s been over 3 years since I wrote the original article about pimping out Irssi, with various themes, scripts, aliases, etc. Well, I figure it’s probably time for an update. After all, if you know anything about me, you know I’m an IRC junkie with Irssi, and currently having a love affair with Bitlbee.

Aliases
I’ve only added two aliases to Irssi since we’ve last met. The first alias comes from the main Irssi.org website. If you scroll to the bottom of the page, there is a tip close to the end for adding all open channels to your “/channel list”. The only thing it was missing was saving the window layout to the config, so next time you open your Irssi, not only will you be rejoined to all of your channels, but they’ll all be in the same place they were last time. Here’s the alias:

/alias CHANNADD script exec foreach my \$channel (Irssi::channels()) { Irssi::command(“channel add -auto \$channel->{name} \$channel->{server}->{tag} \$channel->{key}”)\;}; layout save; save

This next alias will effectively “mark all as read” for your channels. For whatever reason, you may like to have a clean slate for channel activity in your statusbar, rather than all the channels showing some form of activity. This alias will clean up your statusbar, so any new activity becomes immediately available. As mentioned, think of this as “marking all channels as read”:

/alias READ script exec \$_->activity(0) for Irssi::windows

Scripts
My scripts have changed a little bit, but not by much. Really, there’s only two scripts worth mentioning about that I haven’t already done so in the previous post.

The first script is similar to “screen_away.pl“, except for tmux(1). I’ve adopted nesting Irssi behind tmux(1) instead of screen(1) because I just couldn’t get bolded black and white to work correctly. Now, everything looks as it should, with zero formatting issues. At any event, “tmux_away.pl” does the same thing, in that it sets your “/away” status when you detach your session, and resets it when you reattach.

The second script is “trigger.pl“. This script is mostly a search/replace script for events that happen in the channel. For example, if you don’t like the “F-word”, you can change it to something less vulgar with trigger.pl. It can handle much more, but I only use it mainly for that purpose. The triggers I’ve set up this far are as follows:

-publics -regexp ‘Message from unknown participant ‘ -replace ”
-all -nocase -regexp ‘</?(a|b|body|div|em|font|i|s|u)( +\w+=”.*?”)*>’ -replace ”
-privmsgs -nocase -regexp ‘&amp;’ -replace ‘&’
-privmsgs -nocase -regexp ‘&gt;’ -replace ‘>’
-privmsgs -nocase -regexp ‘&lt;’ -replace ‘<'
-privmsgs -nocase -regexp '&quot;' -replace '"'
-publics -masks 'update!update@identi.ca' -channels '&bitlbee' -regexp '^aaron: ' -replace ''

All of my triggers are Bitlbee triggers. Let’s cover each trigger that I’ve created, just so there’s no confusion:

  1. When joining Jabber MUCs with Bitlbee, the Jabber server you’re connecting to can be configured to print the past 20 lines (or whatever) of the previous log, so you can get caught up to speed on the discussion quickly. However, if the user that said something in that log is not in the MUC when you join, you’ll see “Message from unknown participant” in the backlog. This trigger removes that completely.
  2. When Pidgin or Adium users get online, sometimes the clients send HTML/XML to Bitlbee. THis trigger strips the HTML/XML tags as listed completely.
  3. Similar to trigger #2, this trigger replaces the HTML “&amp;” with “&”;
  4. Similar to trigger #2, this trigger replaces the HTML “&gt;” with “>”;
  5. Similar to trigger #2, this trigger replaces the HTML “&lt;” with “<";
  6. Similar to trigger #2, this trigger replaces the HTML “&quot;” with ‘”‘;
  7. I use Identi.ca with the XMPP bot in the “&bitlbee” channel. I know the bot is addressing everything to me, so I don’t want to see each notice begin with “aaron: “, so I’ve stripped that out completely, so the notice actually starts with the user nickname. If you’re interfacing with the bot in a private channel, rather than in “&bitlbee”, then this trigger won’t do much good for you. You’ll need to modify it.

Theme
As much as I try to do a new theme, I always come back to my custom-built “madcow.theme” called “88_madcows.theme“. It’s the awesome. Screenshot

Fully Mobile

This blog is now fully mobile. If you visit http://pthree.org with your mobile browser, you should be taken to a mobile version of the site. It’s only using browser detection, rather than domain mapping, as I’m not in the mood to create A records for m.pthree.org, which only ends up making the URL longer anyway. This has been up for a while.

Mobile screenshot of http://pthree.org

Further more, I’ve added shortlinks to every post. Rather than the lengthy pretty URLs of http://pthree.org/2001/07/22/fully-mobile, you should be able to also visit http://pthree.org/?p=1956, and reach the same place. You can find the shortlinks on the left side of each post from the main page, or at the bottom of the post, when at a specific post. This makes it nicer to type in your mobile device, or share with users via the various messaging options- SMS, IM, IRC, Twitter, Open Microblogging, etc. You can click on the title for the permalink.

If that’s not enough, I’ve taken the shortlink of each post, and created a QR Code from it, in case you are at the computer with your phone, and wish to read the post at a later date. It’s located at the upper left of the blog site. It won’t appear on the mobile version of the site (that wouldn’t make much sense, now would it?). If at the main page, it is the URL of the blog. You’ll even find a QR Code at my contact page (which will actually show on your mobile browser- meh).

I’m ready for the mobile revolution.

OpenSSH Best Practices

This post comes from Matt Taggart, who put together a document about the best practices for using OpenSSH. A lot of the points brought up in that document rang the bells of common sense, and are so good, it’s worth blogging about in hopes that the points mentioned therein reach as many as possible. I’ve also added a couple extra points that I’ve learned with my experience using OpenSSH.

These are best practices from the client perspective, not the server. Many of these points you will have already been familiar with, but some of them not as much. If you sit down and think about what you are doing as a client when you SSH to a server, some of the implications mentioned here make sense.

Lastly, security is a big topic, and not something that can be flipped on and off with a switch. Security always starts with the user. Unfortunately, increasing your security could mean making usability more of a pain in the rear. However, as an OpenSSH client, I hope the techniques mentioned here won’t decrease your usability too bad, while greatly increasing your overall OpenSSH security. With that said, let’s get started.

0. Use ECC first, then RSA, then DSA with maximum bit strength.
When generating your OpenSSH keys, you should be aware of the cryptographic algorithms of the OpenSSH server that you are accessing, and what you can and cannot use. As of OpenSSH version 5.7, elliptic curve cryptography is a supported algorithm. It is proving to be a very secure, robust and light crypto algorithm, but it also must be supported by both the client and the remote server. This means that both the client and the server must be relatively new installations of OpenSSH- something that RHEL 6 and earlier, Debian GNU/Linux Stable 6 and earlier, Ubuntu 10.10 and earlier, and likely many other stable releases from other GNU/Linux operating systems, do not support. When you can, use elliptic curve cryptography for your SSH keys.

If ECC is not available on either your client or server, then you should choose RSA as your key’s crypto. DSA suffers from a weakness, where if the host does not have a sufficiently strong pseudorandom number generator (PRNG), then the “random k” could become exposed from the public key, allowing the attacker to build the private key from the public. The PRNG supplied by GNU/Linux (the device file “/dev/urandom”) is sufficiently strong, providing good random data from entropy pools- thus, GNU/Linux generally doesn’t suffer from this problem. Other operating systems could.

A great demonstration of DSA’s weakness can be found in this excellent blog post, where the author demonstrates how trivial it is to build the private key when the “random k value” is known. Fortunately, RSA does not suffer from this weakness, and also allows you to build larger keys than DSA.

If neither ECC nor RSA is supported by the client nor server, as is the case with some archaic proprietary SSH implementations, then DSA is your only option. Unfortunately, it is also the default for OpenSSH when generating a key. So, you should always get into the habit of passing the “-t [type]” switch when generating your keys.

In all 3 cases, where possible, you should choose the maximum bit strength that the algorithm allows. This will put a bit of strain on the client’s CPU, but it will also give you the greatest strength when authenticating on the wire. When generating your key, use the “-b [size]” switch to specify the bit strength.

1. Use SSH keys and make your servers require them.
There are three reasons why you would want to use SSH keys:

  1. SSH keys with a passphrase provide two-factor authentication.
  2. SSH passwords can be read in plain text on the remote server.
  3. SSH keys aren’t subject to brute force dictionary attacks, like passwords.

Let’s cover each in detail. First, two-factor authentication. SSH keys use public key cryptography. You are given a private and public key when generated. During generation, you are asked to provide a passphrase for the private key. DO NOT GIVE IT AN EMPTY PASSPHRASE! By providing a passphrase to your key, you have enabled the two-factor authentication- something you have (the key) and something you know (the passphrase). Using SSH keys can be troublesome, however. As a result, take advantage of the SSH agent for your system to cache the passphrase locally on your client. This will increase your usability by only entering your key passphrase once, and using the agent to login to other servers without providing the key passphrase again.

Second is reading the user password in plain text on the remote SSH server. You may not think this is possible, as everything in OpenSSH is encrypted, right? Wrong. The two Achilles Heel’s in the connection are the client and servers themselves, where the decryption is taking place. Other users, specifically those who have superuser access, can exploit this. To demonstrate this, make a connection to a server that you have superuser access on. Then, from the client initiate a connection that would require your server password, but don’t supply it. Go back to the server, and find the process of the connection, and run an strace on the PID. Go back to the client, and type in your password. Watch, very likely in horror, the password be displayed on your console.

Here is an excellent writeup by Joseph Hall on this very issue. The problem lies in whether or not you trust those who have superuser access on the server. You should only trust them enough to do their job on the server, and nothing more. Just because they have superuser access on the server, doesn’t mean they can be trusted with your banking account information. Because people use the same passwords over and over across multiple accounts, it’s likely that the password sniffed out of the connection is the same password for their email account. Or bank.

Third, as should be obvious, SSH keys aren’t subject to brute force dictionary attacks like passwords are. If you control the SSH server, and require that SSH keys are the mode of authentication, then brute force attacks will be in vain, regardless how long they try. If you have a publicly facing SSH server, you’re likely aware of how hard your server gets hit from attackers all over the world. By forcing key authentication, all those attacks are in vain.

2. Don’t use a blank passphrase on your keys.
This should come as no surprise, but needs to be mentioned. Your SSH keys are something that should be guarded carefully, with sufficient paranoia. If for any reason, your SSH client is compromised, your SSH keys are a way in to the remote servers that you have access to. If your keys are not protected by passphrases, then after scouring your shell history, or SSH config for hosts to connect to, they’re in the SSH server with little effort. You must protect your keys with strong passphrases!

Now, I understand that there are some like me, who use SSH as the connection for nightly local backups, at which point the client will be asked for the passphrase of the SSH key. Because you wish this to be an automated process, and likely when you’re in bed, you won’t be available all the time to provide the credentials. So, you create an SSH keypair that is not passphrase protected. In such a scenario, here is what I would do:

  1. Only install this key on the backup SSH server, and no where else.
  2. Do not install this key into an account that has superuser access.
  3. Do not install this key into the superuser account.
  4. On the backup server, change the key entry in the authorized_keys file to only allow connections from that client using that key (documented how below).

The first, second and third points are easy enough to configure, but how do you configure the fourth point, and is it even possible? When you copy the key to the authorized_keys file on the SSH server, it could look something like this:

ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAzoblHIUARNP5Kq12QwUqxB6T7m8TWti4LIFcvOCa...

Change the beginning of that entry to this:

from="10.19.84.10",command="/home/user/bin/validate.sh" ssh-rsa AAAAB3NzaC1y...

This tells the server that the only connections allowed to use this key can come from “10.19.84.10″, and when the connection is made, a local script is ran called “validate.sh”. Here are the contents of that script for me:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/sh

case "$SSH_ORIGINAL_COMMAND" in
    *\&*)
        echo "Rejected"
    ;;
    *\(*)
        echo "Rejected"
    ;;
    *\{*)
        echo "Rejected"
    ;;
    *\;*)
        echo "Rejected"
    ;;
    *\<*)
        echo "Rejected"
    ;;
    *\`*)
        echo "Rejected"
    ;;
    *\|*)
        echo "Rejected"
    ;;
    rsync\ --server*)
        $SSH_ORIGINAL_COMMAND
    ;;
    *)
        echo "Rejected"
    ;;
esac

Make sure the script is executable by the user account on the SSH server, and test it before committing to it as part of your backup policy. If the client host is behind a dynamic IP address, or some other variable that prevents it from having a static address, you can remove the “from=” part, but leave the “command=” part. The goal is to minimize damage that can be done with that key.

Again, this is all if you need to perform an automated backup with SSH keys, where a passphrase cannot be performed. In almost every other case, your SSH key should be protected by a good, strong, loaded with entropy passphrase. Using one from a passwordcard is probably best.

3. Use a separate key for every client you SSH from.
I admit that when I first started using SSH, this didn’t make much sense to me. The amount of keys that I generated was a lot, and managing them became somewhat of a pain. Then, when becoming system administrator of a large organization, and controlling upwards of 300 servers, managing that many keys become immensely intense.

I soon came to the realization that it wasn’t that big of a deal. It is trivial to copy the key to the remote host (this can be done with the “ssh-copy-id(1)” command). Further, for work SSH keys, while I am in charge of managing those keys, I should only worry about work keys at work, and home keys at home. In other words, separate the management of the keys.

But the point of this is to NOT copy the same client key to multiple clients. Think about it. By copying the key around to multiple clients, this means that the key is on every server you ever access from those clients, even if some of the other clients cannot access that server directly. Thus, if a client is compromised, and the key is stolen, it’s difficult to know which client was compromised, and all servers that have that key in their authorized_keys file, are subject to compromise. If you have a different key for each client, then those keys are only on the servers that the client has direct access to, and should a client become compromised, you know which servers to saefguard, and damage is minimal.

4. Limit the number of clients you SSH from.
If an attacker can compromise your client, then they can get access to your SSH keys, as they are stored on the filesystem. Further, they may be able to install a keylogger to log passwords and passphrases, including those for your key. Once this information is gained, then all the accounts on the servers the key is installed on are now compromised as well. By limiting the number of clients you SSH from, you minimize the exposure of SSH servers to the attacker.

5. Don’t “chain” or “loop” logins, but do “star”.

The point relates to the one above it, namely limiting the number of hosts you SSH FROM. There are a few scenarios on how you can create SSH sessions:

  • Chain: As a client, you make a connection with an SSH server. Then, from that server, you make another connection to a different SSH server. Once, twice, three times or more, you’ve created a chain of connections from the client to the final host.
  • Loop: As a client, you make a connection with an SSH server. Then, from that server, you make a connection back to the client you started from, thus creating a loop with your connections.
  • Star: As a client, one connection is made to an SSH server. If another connection is needed to a different SSH server, this is made from the client. For each connection, the original client makes it.

The reasons why this is a “best practice” might not be obvious. Let’s start first with chaining connections. If one client is compromised in the chain, the other clients in the chain might possibly be compromised using the same method. Thus, all connections in the chain could become compromised. And a loop is nothing more than a specific instance of a chain.

Of course, this isn’t always possible. Maybe a chain is the only way to get to an SSH server on a private VLAN or behind a DMZ. These connections might be necessary (typically called “jump hosts”), but they should be used with caution, and as little as possible. When you are done with your task, rather than idle the SSH connection, terminate it to minimize exposure, should an attack occur.

When using a jump host, install netcat(1) on the jump host and use the ProxyCommand configuration paramater. Something like this would be sufficient:

Host inaccessiblehost1 inaccessiblehost2
   ProxyCommand ssh accessiblehost nc -q0 %h %p

With star connections, you minimize the risk of compromise with each of your connections, but security is maximized, even if extra work is required on your end. For example, if you wish to transfer data from one SSH server to another, this may mean bringing the data to the client, then sending it to the destination server.


6. Consider disabling the SSH server on the client you are connecting from.
This rule shouldn’t apply only to the SSH server, but to any daemon you have running on your machine. If you don’t need a service running, then turn it off. By doing so, you minimize the attack vector and greatly increase your security. OpenBSD prides itself in having only two remote holes in the default install in a heck of a long time, but then it also doesn’t have any services running on a default install either.

So, for SSH, because you followed rule #5, and you aren’t doing “chain” or “loop” connections from your client, then this means that you’re not connecting to your own machine that you started your initial connection from. I understand that this isn’t always possible. I have 300+ SSH servers at work, and I can’t possible turn off the SSH server on a host, just because I’m connecting from it. But then, do I need an SSH server on my virtual laptop? Not likely, and if there are things I need, I can turn it on, do my work, then turn it off.

7. Don’t ignore SSH host key warnings.
When you install an SSH server for the first time, it creates a server public and private keypair. This set of keys is what is used for the encryption and decryption between your client and the SSH server. Thus, all traffic that you are sending to that server, is done because you trust that the SSH server key presented to you, is indeed the key of the server itself. So, what happens when you connect a different time, and your client warns you that the public SSH server key has changed? Should you trust the connection?

Depends. Usually, it’s due to the fact that you either reinstalled the SSH server or reinstalled the operating system. In this case, you can move forward, so long as you know that the key presented is the new key from the server. However, someone could setup a proxy SSH server, for the intent of gaining system passwords. Your client will warn you the key is different, and you should pay attention to the warning.

So, in your SSH client config, you generally should not set the following:

Host *
    StrictHostKeyChecking no

Default is “yes”, and it should stay yes in your config. OpenSSH is verbose enough for your benefit. Try to take advantage of it, rather than silence it, or ignore it. After all, it’s your data.

8. Be wary of using X11 forwarding.
While taking advantage of the ability to run remote X applications locally on your client is nice, it has some very grave drawbacks. For example, it’s common for people to launch a remote browser, such as Firefox. What isn’t realized, is that you’re providing usernames and passwords through the browser, which could be caught on the remote machine from which the app is running (taking advantage of X events, for example).

There is a time and a place for X11 forwarding, and I have benefited by it, but generally, it’s not needed. Set the following in your SSH client config, and only enable it when needed:

Host *
    ForwardX11 no

9. Don’t use agent forwarding.
As with X11 forwarding, you are giving ultimate trust to the remote host when forwarding your local agent. If that connection makes a connection to an account with superuser privileges, then a user on the remote SSH server could hijack your agent by connecting to the socket the SSH server creates.

Also, on the client initiating the connection, the superuser must be trusted, which isn’t always the case. The local superuser can access the agent socket on the client, and attack. Thus, it’s generally not a good idea to enable agent forwarding. Thus, as it is by default, the following should be sent in your client SSH config:

Host *
    ForwardAgent no