Symfony 1.3/1.4 and Suhosin

I read about Symfony some time back when I was working on a project in CakePHP. Symfony struck my interests primarily because it uses Doctrine (by default) as its ORM, and I’ve used Doctrine in a couple of other projects. This weekend, I elected to give Symfony a try. After reading through the documentation–which I’ll usually do for a few hours before taking the final plunge–I was satisfied that Symfony would be a great framework to learn next.

Updated March 2nd, 2010. Click here to view my updated thoughts.

Following the initial guide was easy until I attempted to view the example application. Then I encountered this:

Fatal error: SUHOSIN – Use of preg_replace() with /e modifier is forbidden by configuration in /home/bshelton/phpapps/sf-test/lib/symfony/lib/response/sfWebResponse.class.php(409) : regexp code on line 409

Uh oh! This struck me as odd, considering Symfony prides itself on being a secure-by-default framework and it triggers a Suhosin warning from the stock install? Great. But don’t be too alarmed as the offending code isn’t a security hole (newlines were inserted by me to increase readability on the web):

return preg_replace('/\-(.)/e',
  "'-'.strtoupper('\\1')",
  strtr(ucfirst(strtolower($name)), '_', '-'));

The Fix

While the /e modifier does have the potential to execute PHP code, the offending line merely takes the first character immediately following a “-“ and uppercases it (the strtoupper call is the only eval’d code). However, rather than disable parts of Suhosin–which could be bad if third party code is included that also does something similar and requires auditing–I decided to fix the issue. According to the Suhosin docs, the fix is fairly simple. Simply change line 409 in symfony/lib/response/sfWebResponse.class.php to:

PHP 5.2 and below:

return preg_replace_callback('/\-(.)/',
        create_function('$matches', 'return \'-\'.strtoupper($matches[1]);'),
        strtr(ucfirst(strtolower($name)),
        '_', '-'));

PHP 5.3 and up:

return preg_replace_callback('/\-(.)/',
        function ($matches) { return '-'.strtoupper($matches[1]); },
        strtr(ucfirst(strtolower($name)),
        '_', '-'));

In this case, rather than evaluating PHP code as part of the replacement, a callback function is created that performs the same approximate test. Obviously, the solution for PHP 5.2 and below could be equally as dangerous, but if we’re careful, we can create a function exactly as we intended.

Performance Concerns

After I discovered this solution by browsing the PHP documentation, it occurred to me that callbacks in preg_replace_callback are slightly slower than performing a call to preg_replace without callbacks. I couldn’t recall precisely how slow, so I elected to perform a benchmark using several different ideas at tackling this particular problem. This section highlights these benchmarks along with each potential solution. Ironically, using preg_replace_callback is about 30% slower than performing character-by-character replacement.

The Methodology

The methodology I used to test various solutions consisted of the following steps:

  1. Generate a large data set to aid in characterizing performance differences and elevate measurable performance discrepancies above the noise floor
  2. Write each solution such that it consumes the data generated in step 1
  3. Compare the performance of each method against the stock Symfony solution

Since the stock Symfony code is designed to “normalize” (their words) headers generated and sent to the client, the source data is created by a script that picks a random number of characters (all lowercase) and joins them together using a dash (-) or an underscore (_) in order to emulate strings like “content-type” or “content_type.” The same data set is used for all subsequent tests. No more than one dash or underscore is used per string; although this is unlikely cause for much concern as most headers are unlikely to have more than one or two separators.

You can download the script that generates this data, along with the source data itself, in the archive toward the bottom of this post.

Note: These solutions were tested on PHP 5.2 only. You’ll likely discover differences when testing on other PHP versions.

The Results

Before we examine each solution, let’s take a look at the results:

Benchmark Plot

As you can tell from this chart, the Suhosin-recommended solution of using preg_replace_callback is the slowest. The stock Symfony code performs rather well but it still slower than simplified string replacement calls. We’ll examine each solution in the following section.

The Code

The code for each solution is provided below along with a brief description of what it does. The actual benchmarks (and benchmark data) is also provided. Remember that each of these solutions is modified to use our source data.

Solution 1: Stock Symfony Solution
<?php
 
include_once 'source-data.php';
 
foreach ($source as $s) {
    preg_replace('/\-(.)/e', "'-'.strtoupper('\\1')", strtr(ucfirst(strtolower($s)), '_', '-'));
}

The stock Symfony solution to the normalization problem is to first convert the string to lowercase, capitalize the first character, and translate all underscores (_) into dashes (-). preg_replace is then run and evaluates the replacement, which converts the first character immediately following a dash to its uppercase equivalent.

Solution 2: preg_replace_callback
<?php
 
include_once 'source-data.php';
 
foreach ($source as $s) {
    preg_replace_callback('/\-(.)/',
        create_function('$matches', 'return \'-\'.strtoupper($matches[1]);'),
        strtr(ucfirst(strtolower($name)),
        '_', '-'));
}

As hinted by the Suhosin documentation, preg_replace_callback is recommended over evaluating PCRE replacements. Unfortunately, this solution is also the slowest. In structure, it is most similar to the stock Symfony code but replaces the evaluated code with an anonymous function. I have not tested true anonymous as presented in PHP 5.3, however. Given that create_function likely has to create an additional interpreter instance in PHP 5.2, this solution might be slightly faster in later versions of PHP when using this code:

return preg_replace_callback('/\-(.)/',
        function ($matches) { return '-'.strtoupper($matches[1]); },
        strtr(ucfirst(strtolower($name)),
        '_', '-'));
Solution 3: Array and String Manipulation Only
<?php
 
include_once 'source-data.php';
 
foreach ($source as $s) {
    $s = strtr(strtolower($s), '_', '-');
    $tmp = explode('-', $s);
    foreach ($tmp as &$t) {
        $t = ucfirst($t);
    }
    $buf = implode('-', $tmp);
}

This solution was among the fastest but its performance remains within the margin of error and may therefore be tied with Solution 4. As with solutions 1 and 2, this solution translates all characters to lowercase and replaces all underscores (_) with dashes (-). However, unlike the previous solution, this one splits each header along the dash boundary, loops through the remaining items, converts them in-place using ucfirst, and then joins them together again with a dash.

This solution is not optimal, and I expected it to be among the slowest. I was surprised to discover that this solution performed faster than the others, and I initially assumed the overhead of preg_replace was due in no small part to the requirement of loading the PCRE engine. It is also likely that increasing the number of split points in the header (by way of more dashes) will likewise increase the amount of time this solution requires to run.

My presumed explanations for the performance of this code segment were challenged with the next test.

Solution 4: Two Replacements
<?php
 
include_once 'source-data.php';
 
foreach ($source as $s) {
    $s = strtr(ucfirst(strtolower($s)), '_', '-');
    preg_match('/\-./', $s, $matches);
    str_replace($matches[0], strtoupper($matches[0]), $s);
}

I confess that the file name for this test is slightly misleading, and I’ll correct it in the posted archive. The initial intention was to utilize two preg_replace statements, but I elected (at the last minute, no less), to use only one in conjunction with an str_replace. In this solution, a dash (-) followed by any single character is captured, capitalized, and then replaced into the final product. As with Solution 3, this is among the fastest of the 5 tested. This solution may also scale slightly better than Solution 3 for headers containing more than a single dash.

Note that the performance of this solution hints that the slightly slower behavior of solutions 1 and 2 are likely due to code evaluation rather than the overhead of loading PCRE.

Solution 5: Character-by-Character Replacement
<?php
 
include_once 'source-data.php';
 
foreach ($source as $s) {
    $s = ucfirst(strtolower($s));
    $buf = '';
    for ($i = 0; $i < strlen($s); $i++) {
        if ($s[$i-1] == '-')
            $buf .= strtoupper($s[$i]);
        else
            $buf .= $s[$i];
    }
}

I initially assumed this would be the slowest performing benchmark of the 5. I was surprised to discover that it is the second slowest. Indeed, this solution performed approximately as well compared to preg_replace_callback as the stock Symfony code did in contrast with this solution.

Conclusion

The Symfony stock code is quite fast but still appears to create instances (at least in sfWebResponse.class.php) where partial evaluation of PHP code is necessary. eval‘d code isn’t necessarily evil, and while it most certainly is a vector for exploitation, it is the manner in which code is evaluated that makes it dangerous. Regardless, I think it is appropriate to evaluate (I made a pun!) circumstances in which code itself is eval‘d and question whether such calls are necessary. While these benchmarks are admittedly highly artificial, it is fairly obvious that in some situations, less code does not necessarily translate to better performance. More importantly, highly compressed code can be difficult for new maintainers to understand and therefore become more error prone or more likely to encounter breakage than simpler but more verbose statements.

The benchmarks listed in this article may be downloaded here, along with the spreadsheet used to chart the data points (apologies that it is in .xlsx format; I’ve been testing the Office 2010 beta–I’ll post a version with an .ods later!). Please recall that this benchmark isn’t scientific. The tests I conducted are highly artificial and are presented for only an exceedingly small subset of data variation. It is likely that other methods are faster, more efficient, and more appropriate for the given solution. Indeed, the entire purpose for this exercise was two-fold: 1) To avoid having to make any configurational changes to Suhosin and 2) surprise myself with how many unique solutions I could create for a single problem. I think I succeeded on both counts.

If you post commentary, please keep in mind that this was conducted for my own purposes and curiosity only. It is neither intended to be malicious to the Symfony project nor issued as a correction to their sources (though a patch that eliminates the use of /e in preg_replace would be nice!). I’ve been highly impressed by the Symfony sources. Unlike most PHP code, they’re clean, concise, easy to understand, and well-documented. It’s a breath of fresh air compared to a vast majority of PHP-based projects. My thanks to the Symfony project in general and Fabien Potencier in particular. Please feel free to post corrections to my methods but be polite about it!

Recommendations? I’d suggest using solution #4 if you’re encountering issues with Suhosin and Symfony.

Updates: March 2nd, 2010

I’m growing increasingly less impressed with Symfony and its internal design. It appears the developers have a strong affinity for preg_replace‘s /e modifier. Yes, I understand, you audit your code and it’s secure. But do you know what the most significant problem is with suggesting users disable Suhosin’s suhosin.executor.disable_emodifier flag is? Users are likely to do it globally–rather than in an .htaccess file somewhere–and as a consequence, they’ll likely open their systems up for (admittedly unlikely but possible) far worse things. I haven’t tried Symfony 2.0 yet, but I hope they’ve resolved this. It’s stupid. And it pisses me off.

Anyway, if you’re looking for some quick fixes and are going through the Symfony tutorial and do not want to disable any part of Suhosin, here’s what you’re going to need to do.

First, change line 409 in symfony/lib/response/sfWebResponse.class.php to:

    $name = strtr(ucfirst(strtolower($name)), '_', '-');
    if (preg_match('/\-./', $name, $matches))
        return str_replace($matches[0], strtoupper($matches[0]), $name);
    return $name;

Then change line 281 in symfony/lib/form/addon/sfFormObject.class.php to:

    if (preg_match_all('#(?:/|_|-)+.#', $text, $matches)) {
        foreach ($matches[0] as $match)
            $text = str_replace($match, strtoupper($match), $text);
        return ucfirst(strtr($text, array('/' => '::', '_' => '', '-' => '')));
    }
    return ucfirst($text);

Naturally, you’re probably better off listening to the advice of the developers directly, but this is my solution. Your mileage may vary.

Note to the developers: If you stumble upon this post in the near future (obviously this doesn’t apply to versions of Symfony beyond 1.4), feel free to add your commentary. Be mindful that some of us actually want to leave suhosin.executor.disable_emodifier set to on, including for your product. I will admit that the lines of code you’ve written look reasonably safe and do not appear to be accepting tainted input, but I’m not going to risk that. I’ve been running several versions of phpBB–and we all know the sorts of holes that software has–along with WordPress and a few other PHP-based web apps without ever having encountered this issue before. Seriously, it makes me kind of worried about the rest of your code! Let’s take a look at the comments in the Suhosin INI file:

; The /e modifier inside preg_replace() allows code execution. Often it is the
; cause for remote code execution exploits. It is wise to deactivate this
; feature and test where in the application it is used. The developer using the
; /e modifier should be made aware that he should use preg_replace_callback()
; instead.

‘Nuff said.


Here’s a good source on preg_replace, why you should always use single quotes, common mistakes, and why you should really just avoid using /e in the first place.

No comments.
***

Fun with find

A friend of mine was asking how to append a string to files contained in a directory structure of unknown depth. I dug around a little bit and found this gem.

Eric has been having several difficult issues building KDE 4-point-something on Funtoo (a Gentoo fork) and it occurred to him that it might be possible to add a specific use flag to every IUSE contained within the build. Unfortunately, due to the nature of the package directory structure, it would prove tiresome attempting to append the same string to each file. Besides, that’s what scripting is all about, isn’t it?

Here’s one possible solution:

find . -type f -name 'IUSE' -exec sh -c 'echo "exceptions" >> {}' \;

For a more secure solution, use -execdir:

find . -type f -name 'IUSE' -execdir sh -c 'echo "exceptions" >> {}' \;

If that syntax frightens you, for loop constructs are also a possibility:

for file in `find . -type f -name 'IUSE'` ; do echo "exceptions" >> $i ; done

If you know of others, share them!

No comments.
***

IPv6, an Experimental Overview

The Internet as we know it is destined to change. That may seem like a profound statement, but it effectively and correctly captures the essence of the Internet’s entire history. Soon–or hopefully very soon–we’ll be witness to one of the most significant transformations made to the very core of how the Internet operates.

I am of course talking about IPv6, the fundamentally-changed and massively-upgraded addressing scheme intended as a replacement to what we’re currently using, IPv4. You may be wondering why IPv6 is such a big deal, and if you haven’t heard of it yet, you should take some time to learn more. There are quite a few compelling reasons pertaining to why we need IPv6, but the most important is simple: We’re running out of publicly-addressable IPv4 addresses. According to Hurricane Electric’s statistics, we have less than two years before the complete exhaustion of our remaining IPv4 pool.

Knowledge is Power: Arm Yourself!

I’m not an authoritative source on IPv6. I’ve simply been testing it for my own diabolical purposes, but there are plenty of places to get started. I know of one particularly excellent blog dedicated to IPv6 fittingly called “Life with IPv6.” You can also find guides for various operating systems. You can find general guides for most operating systems such as this one for gogo.net (formerly Freenet6). There’s also a really good guide on configuring IPv6 for Gentoo Linux, which is general enough (in some sections) to apply to other OSes. If you happen to have a router supported by the DD-WRT replacement firmware, there’s even a guide to configure it. For the FreeBSD crowd, you have the choice of FreeBSD’s official handbook or KAME’s FreeBSD guide.

So what’s this all about?

This rant of mine has its purpose: During my excursion into the new world, I’ve encountered demons, dragons, angels, angry natives, and the occasional mime. While I haven’t any idea where the mime came from, I do know that it is best to share such discoveries. Thus, this post outlines some of the things I’ve encountered, including a few things that don’t seem to be mentioned anywhere. I may also cover a basic ip6tables setup for use in conjunction with an IPv6 tunnel; if not, don’t worry. I’ll be posting something related to that soon.

But above all else, stay away from the little red berries. Those things give you a nasty full-body rash for a week. That poor mime…

Before we begin: Some Caveats

There’s always a “gotcha,” isn’t there? I should mention this before we dive into “getting started,” otherwise you’re liable to come pounding on my door in the middle of the night complaining that I didn’t provide sufficient warning: If you have a separate consumer-grade router rather than a dedicated *nix box, this probably won’t work. You have two choices: Look around for a way to forward protocol type 41 (IPv6) to the target machine or check dd-wrt.com’s router database for your make and model. The latter option certainly isn’t for the faint of heart and it can render your router unusable.

However, there is a silver lining. I have heard that some home router manufacturers are starting to include native support for IPv6 and a few of them even include wireless access points. SixXS (another tunnel broker) maintains a wiki of several well-known brands that support IPv6 and IPv6 tunneling.

I did lie about there being only two options. There’s actually one more, but given my experiences, I wouldn’t necessarily recommend it. Freenet6, operated by gogo.net, is another free and open IPv6 tunnel broker. gogo.net supplies a special client that can work quite well behind a NAT machine (like your router), but the nearest North American endpoint is located in Montreal, Canada. Freenet6 is a great way to test IPv6 if your options are limited. Unfortunately, it’s also painfully slow. (Side note: The sign-up process is obnoxious and creates a “social networking for network professionals” account.)

I suppose there’s also an unspoken forth option: Don’t use IPv6. I don’t really like that option, and you shouldn’t either! Remember: We have less than two years before all of the IPv4 Internet runs out of addresses. Encouraging adoption should be a high priority among Internet-related hardware and software providers. Keep this in mind the next time you purchase a router for your home network–or dust off an old machine and turn it into a routing box. You’d be surprised how easy that really is.

Getting Started

First, if you don’t have access to a native IPv6 network (and that’s what this post assumes; if you do, stop reading now, you won’t find much more useful information!), you’ll need a tunnel broker. Tunnel brokers provide access to a native IPv6 network and, typically, a large chunk of routeable addresses over an IPv4 tunnel. The Gentoo IPv6 guide is a great place to start and includes links to several tunnel brokers around the world. Hurricane Electric is an excellent broker and provides access via tunnelbroker.net. HE also has several locations worldwide, including 10 or so tunnel endpoints across North America. I believe they’ve recently added several new endpoints in Europe.

Hurricane Electric’s tunnelbroker.net service allocates a /64 chunk of routeable addresses and allows you to create up to 5 separate tunnels from different locations. They also provide a full /48 prefix for those in need of a larger address pool, but I can’t imagine anyone who’d be in need of more than 1.8×1019 addresses–which is the address space allocated to a full /64. Better still: Hurricane electric provides configuration samples for several operating systems, including Linux, FreeBSD, and several flavors of Windows. All you have to do is set up your tunnel, pick your external address, and choose from tunnelbroker.net’s configurations what best matches your setup and go from there.

If you’re using Gentoo, the IPv6 guide is mostly safe, but don’t bother following it for configuring your tunnel–you’ll need to follow Hurricane Electric’s suggested configurations for “Linux-route2.” If you don’t, you might wind up being unable to route IPv6 packets between your internal network and the outside world. Don’t say I didn’t warn you.

If all goes well, you should wind up with a new device that looks something like this:

he0       Link encap:IPv6-in-IPv4
          inet6 addr: 2001:470:c:407::2/64 Scope:Global
          inet6 addr: fe80::4800:2c85/128 Scope:Link
          UP POINTOPOINT RUNNING NOARP  MTU:1280  Metric:1
          RX packets:4136 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3342 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:3564671 (3.3 MiB)  TX bytes:492987 (481.4 KiB)

I won’t go over the details–there’s plenty of guides dedicated to setting up tunnels, configuring your kernel, and installing necessary software. If you can’t get the tunnel working, make sure you did something analogous to:

ip tunnel add he6 mode sit remote <SERVER IPv4 IP ADDRESS> local <YOUR IPv4 ADDRESS> ttl 255
ip link set he6 up
ip addr add <CLIENT IPv6 ADDRESS> dev he6
ip route add ::/0 dev he6

You can verify the link state by pinging a couple of IPv6-only sites (use ping6!). First, try the server IPv6 address from tunnelbroker.net; if that works, try these:

$ ping6 ipv6.google.com
$ ping6 www.kame.net

There are many other IPv6-enabled locations. I’ll leave their discovery as an exercise to the reader.

Once you’re able to successfully ping locations beyond your own delegated subnet and Hurricane Electric’s routes, it’s time to move on to more advanced topics.

Router Discovery

IPv6 includes provisions that limit the overall necessity of DHCP. No longer must addresses be delegated by a central host, and IPv6’s auto-configuration provides routing (via discovery) to connected clients. In most cases, DHCP on a pure IPv6 network is only required for supplying name server addresses and other related chores. Even then, I’ve read speculative mumblings on at least one mailing list that some such tasks could be handled via nearest-neighbor discovery. I haven’t yet tested that, however. Windows Vista (and up) already happens to have shaky IPv6 support for anything out of the ordinary.

Depending on your platform, router discovery announcements may be provided by either radvd (most Linux distros) or rtadvd (*BSD). Providing IPv6 access to your network is simply a matter of installing the appropriate package and tweaking radvd/rtadvd’s configuration file. Bear in mind that rtadvd’s configuration is somewhat terser than radvd, though it’s also much shorter. FreeBSD’s handbook has an example for that, too. However, if you’re using some flavor of Linux, you’re in for a real treat. Here’s what my configuration looks like:

interface eth1
{
    AdvSendAdvert on;
    AdvLinkMTU 1280;
    MaxRtrAdvInterval 300;
    prefix 2001:470:d:407::/64
    {
        AdvOnLink on;
        AdvAutonomous on;
    };
};

The above configuration was borrowed almost entirely from the Gentoo IPv6 guide and it works well. There are some caveats, though. If you plan on supplying DHCP via IPv6, you must add AdvManagedFlag on; somewhere after the AdvSendAdvert declaration; if you don’t, your clients won’t ever solicit DHCP requests. As far as I can tell, this isn’t mentioned in any how-to guide that I’ve yet read.

The fascinating thing about IPv6 is that the immediate availability of a router discovery service on the local network will propagate IPv6 addresses to all connected clients that support it. It’s almost like magic (in fact, it is). Try pinging some IPv6 hosts from your clients to prove it!

Linux-only Issues

radvd has a nasty habit of unsetting the sys.net.ipv6.conf.all.forwarding sysctl variable. When it does, connected IPv6 clients won’t be able to do anything via IPv6 and, if available, will degrade to IPv4 access. If you’re having trouble accessing the IPv6 Internet from your clients (or vice-versa), check this sysctl value. You can do so either via sysctl or by examining the contents of /proc/sys/net/ipv6/conf/all/forwarding. If it’s set to 1, then forwarding is enabled and your tunnel may not be working (or ip6tables might be incorrectly configured). If so, keep reading.

You may also encounter an issue where clients are allocated IPv6 addresses via auto-configuration but refuse to access the IPv6 Internet. Under my Gentoo install, this was resolved when at least one IPv6 address from the pool delegated via my tunnel broker was added to the appropriate interface on the routing box. It’s possible that this issue is specific to my setup.

DHCP

DHCP is still somewhat necessary on IPv6 networks where neighbor discovery doesn’t work for domain name resolution services. Unfortunately, there’s a big catch: It works. Partially. This section highlights some of my experiences with two main stream DHCP client/server packages: DHCPv6 and ISC DHCP v4.1.

DHCPv6

DHCPv6 behaves similarly to the WIDE-DHCP implementation. DHCPv6 has also been superseded by ISC DHCP v4.1. I’ve also had somewhat more luck with static IP assignments using DHCPv6. Here are some thoughts:

Pros
  • Most distros provide this as the defacto DHCPv6 DHCP client/server software.
  • Configuration is slightly less verbose than ISC’s DHCP.
  • Lightweight, spartan implementation.
Cons
  • Highly finicky configuration system.
  • New development halted; development is in maintenance mode.
  • Requires slightly more work than ISC’s implementation to work correctly.
Example Configuration
interface eth1 {
    allow rapid-commit;
    option dns_servers 2001:470:d:407::1 2001:470:d:407:0:baad:beef:cafe destrealm.org;
    send information-only;
 
    link AAA {
        allow unicast;
        send unicast;
        send rapid-commit;
        allow rapid-commit;
        pool {
            range 2001:aaa:12:1234::bead:500 to 2001:aaa:12:1234::bead:ffff/64;
            prefix 2001:aaa:12:1234::/64;
        };
    };
    host statichost {
        duid 00:01:00:01:12:aa:23:cb:10:ac:19:83:82:a8;
        iaidinfo {
            iaid 221149200;
            renew-time 1000;
            rebind-time 2000;
        };
        address {
            2001:aaa:12:1234::100/64;
            prefer-life-time 2000;
            valid-life-time 3000;
        };
    };
};
Notes

To a certain degree, I had the most luck with DHCPv6. Static addresses would assign (correctly) to FreeBSD clients and name server addresses would (usually) propagate. Neither Windows Vista nor Windows 7 would accept static IPv6 address assignment; I’m not sure why. Even with the correct DUID-LLT (local link + time), Windows would refuse static assignment. Dynamic addresses worked fine for all OSes I tested.

DHCPv6 version 1.2.x will build under Gentoo but it won’t run. The ebuild is incorrect and the resulting binary will attempt to load data from /var/lib/lib. Fortunately, there is a workaround.

ISC DHCP v4.1

ISC DHCP 4.1 is still very much a work in progress but works fantastic for IPv4 networks and acceptably for IPv6. ISC DHCP is the current defacto standard for DHCP.

Pros
  • Configuration is easy to understand and follow
  • DHCP configuration for IPv6 networks is almost identical to its IPv4 counterparts.
  • As an ISC project, ISC DHCP has a long running track record and earlier versions likely power most corporate and ISP networks.
Cons
  • IPv6 is only starting to stabilize in the still somewhat experimental 4.x branch.
  • Most basic IPv6 features have been implemented but some esoteric ones have yet to be developed.
  • Slightly larger package than DHCPv6; might not be suitable for highly restricted embedded applications.
Example Configuration
default-lease-time 1800;
max-lease-time 7200;
authoritative;
 
option dhcp.domain-search "destrealm.org";
option dhcp6.domain-search "destrealm.org";
option dhcp6.name-servers 2001:470:d:407::1, 2001:470:d:407:0:baad:beef:cafe;
 
subnet6 2001:aaa:12:1234::/64 {
    allow unknown-clients;
    default-lease-time 1800;
    min-lease-time 4000;
    max-lease-time 7200;
 
    # Ranges can be provided in many different ways.
    #range6 2001:aaa:12:1234::bead:10 2001:aaa:12:1234::bead:ffff;
    #range6 2001:aaa:12:1234::10 2001:aaa:12:1234::ffff;
    range6 2001:aaa:12:1234:0:ccee:0:0/96;
}
 
host statichost {
    host-identifier option dhcp6.client-id "00:01:00:01:11:f9:4b:5a:08:00:27:c5:40:c7";
    fixed-address6 2001:aaa:12:1234::500;
}

Note: The “host” declaration can appear inside a subnet declaration. I tend to separate them for my home configurations for aesthetic purposes; don’t do this for larger networks.

Other Thoughts

ISC DHCP supports both IPv4 networks and IPv6. However, it is currently impossible to supply DHCP access to both IPv4 and IPv6 networks at the same time without running multiple instances of dhcpd. It’s possible, and Gentoo certainly makes it easy; however, some tweaks are needed.

The instructions for running multiple instances of dhcpd on the same Gentoo server are somewhat misleading. If you read them, your initial impression would be to simply do something like the following:

# cd /etc/init.d
# ln -s dhcpd dhcpd6
# cp ../conf.d/dhcpd ../dhcpd6
# nano -w ../dhcpd6
# cp ../dhcp/dhcpd.conf ../dhcp/dhcpd6.conf
# # Point /etc/conf.d/dhcpd6's config file to /etc/dhcp/dhcpd6.conf
# # Done!

Unfortunately, this won’t work. Under the checkconfig() function in /etc/init.d/dhcpd (which is now also linked to /etc/init.d/dhcpd6) refuses to honor the DHCPD_OPTS defined in /etc/conf.d/dhcpd. Thus, forcing the server to run in IPv6 mode (with the -6 switch, though IPv6 mode is the server’s default) doesn’t work. Instead, it is necessary as of this writing to create a copy of the /etc/init.d/dhcpd script and modify the function accordingly to include ${DHCPD_OPTS}:

checkconfig() {
        /usr/sbin/dhcpd ${DHCPD_OPTS} -cf ${DHCPD_CHROOT}/${DHCPD_CONF} -t 1>/dev/null 2>&1
        ret=$?
        if [ $ret -ne 0 ]; then
                eerror "${SVCNAME} has detected a syntax error in your configuration files:"
                /usr/sbin/dhcpd ${DHCPD_OPTS} -cf ${DHCPD_CHROOT}/${DHCPD_CONF} -t
        fi
 
        return $ret
}

(Admittedly, the above code may cause problems if the DHCPD_OPTS variable contains -cf or similar switches.)

Furthermore, it is also necessary to point the server to a different lease file and include the following in a separate dhcpd.conf:

pid-file-name "/var/run/dhcp/dhcpd6.pid";

Here’s what my /etc/conf.d/dhcpd6 looks like:

DHCPD_CONF="/etc/dhcp/dhcpd6.conf"
DHCPD_IFACE="eth1"
DHCPD_OPTS="-6 -lf /var/lib/dhcp/dhcpd6.leases"

Also, much like DHCPv6, ISC DHCP won’t supply static addresses to Windows clients. I can only assume this is the consequence of an incorrect understanding of how DUIDs work on my behalf. If I make an insightful discovery or someone posts corrections in the comments, I’ll update these notes accordingly.

Link Local Routing

IPv6 doesn’t really support the notion of private networks. At least, it doesn’t support private networks in the same manner as IPv4. Instead, there are several ranges reserved for router discovery and, more importantly, “link local” addresses. Link local addresses are automatically created whenever IPv6 support is enabled for an interface and exist in the fe80::/16 prefix. Any address in this range is not routeable but can be pinged on the local network.

There is one surprising discovery I made with regards to IPv6’s auto-configuration. On the local network, the link local address of your router actually becomes the gateway for hosts that it has automatically configured. Gone are the *.*.*.1 router conventions of IPv4. This may seem unimportant, but when you consider that it will impact what choices you make with regards to your firewall, it suddenly becomes much more important.

Samba, CIFS, IPv6, and You

I’ve been running Samba on my local network for literally years to supply access to my /home and various file repositories. However, something unusual started happening the day I booted my server with a new kernel including IPv6 support: Windows 7 would announce that it was “unable to connect all network drives” immediately after login. I assumed (incorrectly) that Samba had crashed, and thus opened Windows explorer, double-clicked the drives, and then they mysteriously opened as if nothing were amiss.

After much poking, prodding, and a liberal application of tcpdump I discovered a couple of important things. First, it is important to have Samba upgrade to at least version 3.2 when adding IPv6 to a network (3.0 appears to be resolvable, even though it doesn’t have fully capable IPv6 support). Second, I also learned that IPv6 packets must be routeable to the Samba server–and must be processed by it as well–because Windows Vista and Windows 7 will both attempt to use CIFS over IPv6. If IPv6 queries fail, these versions of Windows will report that attached network drives cannot be mounted even though they appear to degrade successfully to IPv4 access.

Also, one of the more significant contributors to my Samba problems was related to how I had my firewall configured. Being a good netizen and blocking everything (except what I want) by default, I figured allowing access to the local network via eth1 (my internal interface) was enough. That is to say until I realized that I hadn’t correctly allowed my internal network unadulterated access to the server. Moral to the story: Once you get around to setting up ip6tables, double check your settings. I can’t stress this enough.

Chances are, too, that if you’re using Samba, you’ve probably set it up to provide printing access via the local network to Windows machines that don’t yet support IPP. (Of course, if you’re using Windows Vista or Windows 7 x64, you have no other choice than to use IPP but that’s another rant!) If you’ve enabled ip6tables, you might notice a lengthy delay in printing, and searching for a printer will seem nearly impossible. Here’s why:

Feb 19 16:54:39 sagittarius [277797.502535] IN= OUT=lo SRC=0000:0000:0000:0000:0000:0000:0000:0001 DST=0000:0000:0000:0000:0000:0000:0000:0001 LEN=80 TC=0 HOPLIMIT=64 FLOWLBL=0 PROTO=TCP SPT=42045 DPT=631 WINDOW=32752 RES=0x00 SYN URGP=0
Feb 19 16:54:51 sagittarius [277809.502544] IN= OUT=lo SRC=0000:0000:0000:0000:0000:0000:0000:0001 DST=0000:0000:0000:0000:0000:0000:0000:0001 LEN=80 TC=0 HOPLIMIT=64 FLOWLBL=0 PROTO=TCP SPT=42045 DPT=631 WINDOW=32752 RES=0x00 SYN URGP=0
Feb 19 16:55:15 sagittarius [277833.500054] IN= OUT=lo SRC=0000:0000:0000:0000:0000:0000:0000:0001 DST=0000:0000:0000:0000:0000:0000:0000:0001 LEN=80 TC=0 HOPLIMIT=64 FLOWLBL=0 PROTO=TCP SPT=42045 DPT=631 WINDOW=32752 RES=0x00 SYN URGP=0
Feb 19 16:56:03 sagittarius [277881.502542] IN= OUT=lo SRC=0000:0000:0000:0000:0000:0000:0000:0001 DST=0000:0000:0000:0000:0000:0000:0000:0001 LEN=80 TC=0 HOPLIMIT=64 FLOWLBL=0 PROTO=TCP SPT=42045 DPT=631 WINDOW=32752 RES=0x00 SYN URGP=0

Notice anything amiss? The local machine (that’s ::1/128, or all those zeros followed by a 1) keeps sending requests to port 631 but why. What’s wrong?

This is what happens when Samba sends printer list requests to CUPS. Without a reply, it’ll continue trying until it gives up. The fix? Allow localhost. I know it goes without saying, but it’s easy to overlook, particularly in something like iptables. Moreover, when you’re not used to examining IPv6 networks, it’s easy to overlook the rather unusual looking localhost declaration. Besides, there’s no reason not to grant localhost IPv6 access!

Alas, I get ahead of myself. My ip6tables section will be up and coming in a day or two, and I’ll even have a script prepared. Be aware that there are some unusual complications related to some of IPv6’s reserved ranges (more on that later), but by and large, configuring iptables for IPv6 is analogous to IPv4. The only significant difference is that you’ll have more basic rules to contend with to support things like automatic discovery.

See you next time!

No comments.
***