Friday, August 14, 2009
First steps at "real" web bling
Friday, June 5, 2009
D-Link VTA-VR with Asterisk
While walking around a local store, I came upon the clearance isle and found a D-Link VTA-VR in an opened package. Seeing the price was $25 (which read as $15 at the register) I thought I'd give it a try. The goal is to rip it from its Vonage branding and make it speak to my Asterisk server.
It worked, mostly. There are many guides on the net on how to deal with this device, but it turns out the default password was already open, so perhaps someone had already cracked it for me. Thanks, if so.
The box has two phone jacks, but my first goal was to get just one of them working. This turns out to be trivial -- just configure the username, password, and the proxy and away it goes.
The second line turned out to be a problem. This client, like so many other cheap devices, seems to break the SIP protocol. For one, both lines share a single UDP agent port (defaults to 10000, I set it to 5060 for packet capture filter sanity.) This is ok but, when registering at least, Asterisk would often (but not always) report "expired nonce."
What is an "expired nonce" you ask? It is part of the registration protocol. Basically, the SIP device sends a REGISTER requeest without any login information, and it receives an UNAUTHORIZED response. In that response, however, is some information which can be combined with a username and a password that the client and server know, to generate an authentication token. Part of this is called a "nonce" which is really just a little bit of random data that prevents certain security attacks.
What I was seeing is this:
VTA: REGISTER for line 1
Asterisk: UNAUTHORIZED retry with nonce [123456]
VTA: REGISTER for line 2
Asterisk: UNAUTHORIZED retry with nonce [abcdef]
VTA: REGISTER for line 1 with nonce [123456]
Asterisk: Expired nonce [123456] retry with [deadbeef]
VTA: REGISTER for line 2 with nonce [abcdef]
Asterisk: Expired nonce [abcdef] retru with [feedme]
...
The VTA would never recover from this. A bit of random jitter between registration attempts, or only attempting one at a time, would fix this. Using different ports on the VTA device would fix this, but there is no configuration option for that. If the VTA used a different Call-ID for each registration request, it would work.
Unfortunately, there seems to be no way to get both lines working reliably with a single Asterisk server.
There are several hacks I can think of, one is to install a SIP proxy that can register the second line, but would really just proxy the connection to the Asterisk server. Another would be to cause Asterisk to listen on more than one port, and use different ports per line. I don't think that's easy or even possible.
Another option would be to hack Asterisk to make it understand that a very popular firmware is rather broken, and it should just expire a nonce based on more criteria than it uses now. Right now, for a given Call-ID, there can be but one nonce. If a new one is issued, the old goes away. If Asterisk were to maintain a linked list of possible values and expire them all when one is found to be working, this might work. It would delay line 2 registration, but that's quite acceptable.
Myth Busting
I'd also like to dispel some myths that many VTA-VR hacking pages are saying, usually referring to each other in the process.
The VTA-VR uses four UDP ports: One for the shared "agent port", one for each line's SIP proxy (usually both are 5060, this is the port the Asterisk server listens on), and one for TLS (which I do not use, but it defaults to 5061.) You cannot set the proxy port to something other than what the asterisk server is listening on, so any comments like "you need to use different ports" is just wrong, as unless your Asterisk server is accepting connections on more than one port, it won't work.
Setting the "user agent" port to 5060 is handy. If you do this, you can set the defaultip=10.42.1.2 in sip.conf for that line, and even if the device is not registered, Asterisk will still send calls there. This is somewhat scary, but it does seem to work. Sometimes.
Changing the timers does not help a great deal. They are defaults, it's best to leave them alone.
Friday, March 27, 2009
DNSSEC vs Firewall
options {
edns-udp-size 1460;
};
This has the side-effect of causing TCP retries on large packets, which are often the DNSKEY responses. However, it also causes DNSSEC to work, so overall it's a good thing.
Friday, March 6, 2009
A Real XML API and Rails
I recently implemented an XML API that I intended to be used outside of a web browser. Much of the words others have written on the topic are ways to get a Javascript framework to use the authentication_token magic. Some others show the GET side and mention the DELETE but omit the PUT and POST methods.
Here are things I've learned:
- To ensure XML data is returned, use the correct HTTP header:
Accept: application/xml - Rails assumes that multipart forms and url-encoded forms are from browsers. You can't use them in a default Rails setup if you want to avoid the
authentication_tokencheck. - To
POSTorPUT, use a header ofContent-Type: application/xmland include XML data.
It is rather unfortunate that Rails assumes that the encoding ties into a browser. It should be possible to use any encoding so long as the XML data types in the headers are correct. This is probably a bug, but it might be that if you receive XML through an API, you should send XML too.
Example
curl --user user:password -H 'Accept: application/xml' \ -H 'Content-Type: application/xml' \ -X POST -d '<?xml version="1.0" encoding="UTF-8"?> <item> <name>foo</name> <description>bar</description> <price>100</price> </item>' http://localhost:3000/items/create
Tuesday, March 3, 2009
Cox and World Record Customer Support
I get Internet, cable TV, and phone though Cox. Perhaps I'm entirely too picky, but when I pick up my phone, turn on my TV, or want to check my email I expect these "always on" services to be, well, on.
In the last 30 days, I have lost the use of my phone that I have noticed four times, each of which was approximately an hour.
I happened to be on the phone with Dell at the time (Yea, I posed about that mess too.) So, after cleaning up with Dell, I called Cox and asked what happened. The answer was as expected... "We don't know."
Who monitors this sort of thing? What can be done about an ISP and Telco provider who, well, doesn't provide? It's not like things aren't working amazingly well when they work. It's when they fail to work that is the problem.
It seems to me that they intentionally keep the customers in the dark. They intentionally choose to not say if an outage is planned or unplanned. And when they do maintenance at night it is between the hours of 01:00 and 08:00, which is the only time supervisors are not in their call centers. Coincidence? Unlikely.
I'm looking in to what to do about this. Not having a working phone is not only annoying it is downright dangerous. Have to call 9-11? Well, better have a cell. Out of town? Hope your alarm doesn't go off because it cannot make a call for help.
Update! Just last night (06-Mar-2009) my services went out again. I found out from a line tech that this was to "split my node" -- more or less, make two or more network segments from one. This is a good thing, but once again it would have been nice if Cox knew WHY when I asked them the first time...
Below is a graph showing the average ping times to my default router before and after they completed the split. I like the one on the right much better as it is far more stable. Ignore the small outage on the right side, it was expected.
Dell and World Record Customer Support
Recently a message started appearing that told me my A/C adapter was not recognized by the system. Knowing that the A/C adapter and laptop were covered by a next-day on-side warranty, I called Dell. I carefully explained the problem: the batteries don't charge any longer, the boot-time error message, and that the green LED on the adapter seems dimmer than it should be.
The technician at Dell decided that, with this set of problems, the motherboard needs to be replaced. I asked if perhaps an adapter should be tried first... No, he assured me, that would not be the problem.
Two days later (which is service contract for "next business day service") a very friendly and helpful technician arrived, and replaced the motherboard. Same problem. He and I had a good old laugh at Dell for that, and he asked Dell to send a replacement A/C adapter.
Two days later, it arrived. No warning message! Success! But wait... now when I move the laptop it looses power for a brief moment. If there is no battery, it turns off. This was not happening before...
Calling Dell resulted in a mess. The first technician at Dell I spoke with was, to be as kind as possible, a moron. He had me run hardware tests. He had me set the brightness on the laptop LCD to full on and off battery, and since it didn't flicker anymore was fully prepared to declare the problem resolved. I slowly and carefully explained that this is a physical problem and that moving the computer at all causes it to turn off if the batteries are too low or removed.
True to the incompetence that I have come to expect from nearly every computer company's tech support, he declared that since no errors show up in the BIOS self-tests, it MUST be software. I asked to speak to his manager.
The manager declared that this was indeed a problem, part of the ongoing issue, but that I needed to ship the computer to Dell. This is because, in the mean time, my service contract has expired. They admit that while this was an on-going problem, and they will fix it, it won't be done with on-site, and that I have to ship the laptop. I called bullsh*t.
After about 20 minutes of hold-time, two agents, and over 45 minutes of on-the-phone time they finally decided that it was indeed still covered under the same warranty replacement terms as when the problem started, and they will ship another motherboard out and have it replaced again, next-day (in service-contract terms), which means to the rest of us 3 days.
So, so far, to replace a $100 A/C adapter, Dell has wasted five hours of my time and probably two to three times what the laptop is worth in service calls.
Saturday, February 28, 2009
Ruby and OpenSSL
I recently had to do some DNSSEC-type (somewhat low-level) cryptography work, and found the seeming lack of Ruby OpenSSL documentation a big pain. I found numerous examples of how OpenSSL is commonly used with PEM-encoded keys, but precious little information on low-level key loading. To save others the trouble of having to dig up some of this, I've collected some short examples of how to do low-level RSA and DSA building from a lower level than most use.
This table summarizes the variables which need to be set to use an RSA public and private key.
RSA Keys
| Key Type | Item | Description |
|---|---|---|
| RSA Public | e | Public Exponent |
| RSA | n | Modulus |
| RSA Private | d | Private Exponent |
| RSA Private | p | Prime 1 |
| RSA Private | q | Prime 2 |
| RSA Private | dmq1 | Exponent 1 |
| RSA Private | dmp1 | Exponent 2 |
| RSA Private | iqmp | Coefficient |
Thus, in order to make a working RSA public key (so the method key.public_encrypt() or key.public_decrypt() work) you must set at least n and e. For a working private key, you would need to load all of the items. Exposing any of the items marked as "RSA Private" above will cause a key compromise.
RSA Example
In this example, a 128-bit RSA key is loaded from numerical values. In DNSSEC, the public key is stored in the DNSKEY record for the zones. Don't use these numbers for real crypto; the short key length is used only to make the numbers short enough to fit in the screen width. For real work, 1024 is probably a reasonable minimum length for short-lived uses, and 2048 for longer-term use.
require 'openssl'
#
# Build a RSA public key. We only need to load two things
# here in order to use the public key to use it to encrypt,
# sign, or verify.
#
pub = OpenSSL::PKey::RSA::new
pub.e = 65537
pub.n = 216457604585180710748301099018726389113
# At this point, this will work:
crypted = pub.public_encrypt("test")
#
# Build an RSA private key. For the private key to work, we need
# to load the entire key, private and public components. As we
# should have access to both, this is not really a problem.
#
prv = OpenSSL::PKey::RSA::new
prv.e = 65537
prv.d = 178210827022942698143906513631075003381
prv.n = 216457604585180710748301099018726389113
prv.p = 15294921647876231099
prv.q = 14152253249053866587
prv.dmp1 = 6806715058393856237
prv.dmq1 = 637679537428568107
prv.iqmp = 6672106206837437412
# Now we have a working private key.
puts prv.private_decrypt(crypted) # prints "test"
DSA keys
A DSA key is more or less the same, just with different variable names. It is also split into a public and private part, and the key can be loaded from individual components just as easily.
| Key Type | Item | Description |
|---|---|---|
| DSA Public | pub_key | Public Key |
| DSA | q | Prime 1 |
| DSA | p | Prime 2 |
| DSA | g | Multiplicative order modulo p is q |
| DSA Private | priv_key | Private Key |
DSA Example
Unfortunately, this example has some numbers which are too long to display nicely. I have used a trick to convert them from strings into integers so they will fit here. Normally you would not need to do this.
require 'openssl'
#
# Build an DSA private key. For the private key to work, we need
# to load the entire key, private and public components. As we
# should have access to both, this is not really a problem.
#
prv = OpenSSL::PKey::DSA::new
prv.pub_key = ("899167044393666062859565588228279347268072456516837337" +
"963353916587148226144760114643916732975837345856985656" +
"3340384802383806137452386519280693373122367959").to_i
prv.p = ("952649509730281181203079535805855260554748337655197352471196" +
"869232197576949258404031665397657842790773780623545384978542" +
"6685417827665656974405272756289291").to_i
prv.q = 903197981571669745498020976355730183999507610553
prv.g = ("535694721480531756072717909769318961974692885092552247120424" +
"749877864650255208980198391972633196543370921493242375015765" +
"755160911031468160738717891191998").to_i
prv.priv_key = 557886499717422048101097620625259920363848888840
# At this point, this will work:
signature = prv.sign(OpenSSL::Digest::DSS1.new, "test")
#
# Build a DSA public key. We only need to load two things
# here in order to use the public key to use it to encrypt,
# sign, or verify.
#
pub = OpenSSL::PKey::DSA::new
pub.pub_key = ("899167044393666062859565588228279347268072456516837337" +
"963353916587148226144760114643916732975837345856985656" +
"3340384802383806137452386519280693373122367959").to_i
pub.p = ("952649509730281181203079535805855260554748337655197352471196" +
"869232197576949258404031665397657842790773780623545384978542" +
"6685417827665656974405272756289291").to_i
pub.q = 903197981571669745498020976355730183999507610553
pub.g = ("535694721480531756072717909769318961974692885092552247120424" +
"749877864650255208980198391972633196543370921493242375015765" +
"755160911031468160738717891191998").to_i
# Now we have a working private key. Verify the signature
if pub.verify(OpenSSL::Digest::DSS1.new, signature, "test")
puts "Signature verified."
else
puts "Signature verification failed."
end
Find conditions from params[]
I have often wished to add a trivial search capability to my controllers which would allow searching on different fields. Without getting into a mess of many different if statements each of which has a different set of conditions, I use something much like the following:
def index
cond_hash = {}
cond_strings = []
if params[:search]
cond_hash[:login] = "%#{params[:search]}%"
cond_hash[:email] = "%#{params[:search]}%"
cond_strings << "(login ILIKE :login OR email ILIKE :email)"
end
if params[:search_address]
cond_hash[:address] = params[:search_address]
cond_strings << "(address == :address)"
end
conditions = cond_strings.join(" AND ")
@users = User.all :conditions => [ conditions, cond_hash ]
end
It may be safer to use users.login, users.email, and
users.address in the SQL-like strings above.
Rails 2.0 and cool error handling
Rails is a great framework, but it has gained something of a bad reputation in terms of error reporting. Everyone has seen them -- those ugly 500-status "we're sorry, but something has gone wrong" messages.
In a finished application, this just doesn't cut it. It used to be necessary to trap the error using something like this:
def rescue_action_in_public(exception)
case exception
when ::ActiveRecord::RecordNotFound
render :file => "#{Rails.public_path}/404.html", :status => 404
else
render :file => "#{Rails.public_path}/500.html", :status => 500
end
end
The problem is that, as error causes begin to pile up, this method gets messy. Plus, you might want to render something different in one controller than in another, and would either need to duplicate all the logic, put controller-specific cases in the ApplicationController, or call ApplicationController::rescue_action_in_public directly.
Enter Rails 2.x error handling. Drop this in your controller or ApplicationController.
rescue_from(ActiveRecord::RecordNotFound) do |e|
render :file => "#{Rails.public_path}/404_record_not_found.html", :status => 404
end
By building up a rich set of rescue_from handlers in the ApplicationController, and only overriding the ones you wish to make per-controller, you have fine-grained control. And they work exactly the same in development and testing as they do in production.
Thursday, February 26, 2009
Ruby Regular Expression Gotchas
I love Ruby. I love Ruby on Rails. Rarely have I found a language or a framework that just works.
However, you still have to know the finer details sometimes.
I recently made a model for a DNS zone. The name in the model is the "front part" of a fully qualified domain name. For instance, if zone.name = "foo" then I would write the name into my name server's configuration files as "foo.example.com."
Knowing that people were evil, I saw that if a user put a string in like "example.com. NS hackerz-will-someday-rule-the-earth.ru.\nfoo" I would happily write out two strings, one being rather bad.
Knowing how easy this sort of data validation is in Rails, I made my model look like:
class Zone < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :name
validates_format_of :name,
:with => /^[a-zA-Z0-9\-\_\.]+$/,
:message => "contains invalid characters."
end
Happy, I ran a few tests using my browser and found that I could not insert names with spaces, colons, tabs, etc. Then, several days later, I decided it was time to write tests for this.
require 'test_helper'
class ZoneTest < ActiveSupport::TestCase
def test_name_with_newline_fails
z = Zone.new(:name => "test\nzone")
assert !z.valid?
assert z.errors.on(:name)
end
def test_name_with_space_fails
z = Zone.new(:name => "test zone")
assert !z.valid?
assert z.errors.on(:name)
end
end
Imagine my surprise when test_name_with_space_fails() passed, and the one I was most worried about, test_name_with_newline_fails(), did not!
Not all regular expressions are alike
The problem is in what I thought ^ and $ actually matched. I thought these meant "match the beginning and ending of the string." However, it turns out it means "match the beginning and ending of each line contained in the string," where lines are divided by newlines. Ooops.
Changing ^ into \A and $ into \Z fixed this problem. Now I'm auditing all the code in this application to see if there are other problems like this.
This is just one thing to add to an ever-growing security checklist for my Rails work. It's also a very typical security hole: programmer error.
Tuesday, February 24, 2009
Mmm, sharp knives...
Saturday, February 21, 2009
String#bitruncate
And that's '"bi-truncate" not "bit-uncate".
What's it do?
The default options are { :length => 30 } which will produce 15 characters from the front and 15 from the end, putting ... marks in the middle.
For rails, I put this in my lib/core_extensions.rb file.
class String
#
# Truncate from both ends of a string. The :length parameter, which defaults
# to 30, will return the first 15 and the last 15 characters from a string
# if it is longer than 30 characters. If it is shorter, the entire string
# is returned.
#
# Another way to specify the front and back portions are with :flength and
# :elength. If you specify one of these but not the other then you will
# not get the missing part. e.g., :flength => 10 alone will return only
# the first 10 charcters of the string. This is the same as the standard
# truncate(s, :length => 10) helper.
#
# If a :length parameter is provided it will override any other lengths
# specified.
#
def bitruncate(options = {})
maxlength = options[:length] || 0
flength = options[:flength] || 0
elength = options[:elength] || 0
omission = options[:omission] || '...'
if maxlength == 0 && flength == 0 && elength == 0
maxlength = 30
end
if maxlength != 0
flength = maxlength / 2
elength = maxlength / 2
end
return self if length <= (flength + elength)
front = ''
back = ''
if flength > 0
front = self[0..(flength - 1)]
end
if elength > 0
back = self[(length - elength)..(length)]
end
front + omission + back
end
end
Tuesday, May 20, 2008
Vmware Server and Xen
In the past, I've played with VMware (as a "workstation" "server", not the bare-metal one we have access to now) but was never quite happy with it. Some of the problems I had might have been that I ran it on windows Vista, not Linux. However, from a VM point of view, the VM itself should be more or less identical.
Recently I tried out Xen on the same hardware, but using NetBSD/amd64 as the "host" OS.
Hardware
The machine is Gateway GM5446E with a dual core Intel Core 2 Duo with 3 GB of ram. The machine has three SATA hard drives, connected via an Intel AHCI controller running in native AHCI mode.
Bare Hardware Baseline
I booted a standard NetBSD-current/amd64 kernel and ran some speed tests, which gives a baseline for dom0 and guest OS disk I/O speed tests. See below.
VMware
In my VMware install, I used the machine running "Windows Vista Media Center" -- it was what came pre-installed on the machine.
Host OS: Windows Vista Media Center
Guest OSs tried:
- NetBSD-4.0/i386
- NetBSD-4.0/amd64
- NetBSD-current/i386
- NetBSD-current/amd64
- Linux Ubuntu (server, then-current version)
- Linux Debian (then-current version)
Linux booted in 64-bit mode, but would crap out at some later point with similar issues that NetBSD had.
One machine, named "nfsd", was dedicated to serving out home directories and source trees of NetBSD. The other host OSs mounted /home or /netbsd-src from nfsd.
Each machine had a "local" disk to store object files from pkgsrc, src, and other OS-related builds.
General VMware Problems
I could not get netbsd/amd64 (current or 4.0 release) to "self host" -- build /usr/src and kernels -- reliably. They would either silently lock up without reason, or they would crash with an odd CPU exception.
Timekeeping was whacky. Without running the VMware-supplied (closed source) tools on a client, time was off, and apparently in uncorrectable ways. Running ntp made things seriously whacky as the time would drift wildly as ntp tried to correct a guest.
The VMware closed-source tools are only available on a small, limited number of OS types, and then specific versions of many of them. They do supply a .so that is, in theory, linkable on many versions of Linux, but the install procedure warns loudly of warnings pertaining to compatibility.
VMware running on anything but Intel chips with synchronized cycle counters (which most OSs use for high-res timekeeping these days) was a disaster.
VMware Strengths
If the problems above are solved, VMware is a true virtual machine architecture that will run any OS without modification. VMware could run windows guests, right along with unmodified NetBSD, FreeBSD, Linux, and Solaris/x86 guests.
Xen
I tried Xen 3.1.3.
Xen is a different architecture than vmware in that it prefers to use "paravirtualization" rather than a full virtual machine. It has a host machine (called "domain 0" or "dom0") which attaches to the physical hardware and acts as a conduit between the xen hypervisor and hardware.
The boot process is that the xen kernel is booted first, which then boots the dom0 host. Multiple domains can be created, serving different hardware, but in practice this is rarely done.
Each host OS has a config file, and is stated with "xm create /path/to/file.conf". This boots the guest OS and connects a serial console, which can be used with "xm console <name>".
Since the "dom0" is a fully functional OS in its own rights, I have it serve NFS to the guest OSs.
I created the following guest OSs:
- NetBSD-current/i386
- NetBSD-current/amd64
- Windows XP Pro (32-bit)
- Windows Server 2003 (32-bit)
Yes, I managed to install Windows XP Pro and Server 2003. They run in a "vnc" console, and for all practical purposes looks like windows. This is using Xen's "hvm" -- which is a full hardware emulated virtual machine, and allows running unmodified guest OSs. People have Vista running in a virual machine under Xen, but I do not have "real" Vista install media or licenses, just the ones that came with and is tied to my hardware.
Xen also supports both realtime and offline "migration." As I have only one machine of the same type, I have not yet read up on how this works. The basics: A realtime copy is made of the guest's ram, device state, and other data. It is transmitted to the new destination, and synced up until a very small switchover time can be used to swap where that guest is running. Xen claims 100 ms switchover time is possible, but there are restrictions: The disks are NOT migrated, so must reside on a shared volume. The physical network each dom0 is on is also shared, in order to avoid disruption of TCP connections. I also believe fairly identical CPU and dom0 operating systems should be used.
Offline migration involves shutting the guest down, copying the disks over, and restarting it on a new dom0. This will, of course, interrupt service.
Xen Problems
It is difficult to configure for the fist time. The documentation is... lacking. It is also only as solid as the host OS is, but vmware has the same issue in "server" or "workstation" incarnations.
Xen is also very, very "linux" specific in documentation and examples. Most of these can be translated -- I certainly did so easily enough -- but this is being corrected in their documentation as more OSs are able to boot as dom0.
Xen Strengths
Timekeeping in Xen, since it is paravirtualized, is almost perfect. Small drifts will occur without running ntp, but all guests (and the host) can run ntp and obtain sanity.
It also appears that all guests and the dom0 "drift" identically, so this is probably related to hardware timekeeping issues. The measured drift of an uncorrected NetBSD guest was 4 seconds in two weeks. ntp correction kept the others in perfect real-world sync.
It is as free as you want it to be. Support and commercial versions exist, but the free stuff works amazingly well.
Performance
On Xen, all tests were performed with the domu's running but idle, and no hvm guests running (windows is just too unpredictable.) On VMware, only one VM was active at once, and the Vista host was as idle as it could be made.
I measured three main things here:
- Boot speed: How fast a kernel gets from loading to the first /etc/rc message.
- Disk speed: read/write speed.
- CPU Performance.
Boot Speed
The dom0 boots as fast as any other kernel boots; it must probe the hardware, wait for hardware to change state, etc. No measured difference between a standard NetBSD-current/amd64 kernel and the dom0 kernel.
The domUs (guests) boot so fast it is nearly impossible to measure. This is because the devices they have access to are known -- all are on a virtual bus, and are directly enumerable, so there is no need to probe for devices, wait for them to change state, or time out when not present. As best I can measure, just under 2 seconds is a fair estimate.
The hvm (windows) guest seems to be about as fast as windows is. I did not analyze this one much.
On VMware, the host OSs boot at about the same speed as a "real" machine boots unless a custom kernel is built with just "known present" devices. Even then, boot times are 15-20 seconds.
Disk Speed
In all host/dom0 tests, "iozone" version 3.263 was used, with a 1 GB file on the same disk. Each test was performed only once; for real comparison data we'd want to run it more than once, but this is just a first-pass test.
For native NetBSD/amd64, I had to increase the file size to 4 GB to avoid the cache, as the machine has 3 GB of ram.
- wd0 is a 500 GB SATA 3.0Gb/sec disk.
- wd1 is present but unused.
- wd2 is a 320 GB SATA 1.5Gb/sec disk.
All are on different channels of an Intel AHCI controller running in native SATA mode.
For the Xen tests, all disks were mounted as files on the dom0 host. From dom0's point of view, the file is mounted on a "vnd" virtual disk, and that virtual disk is exported to the host.
For the VMware test, all disks were mounted as files in the Windows filesystem.
| OS | Disk | Block Size | Read | Write |
|---|---|---|---|---|
| netbsd-current/amd64 native | wd0 | 8192 | 60762 | 59949 |
| 16384 | 60545 | 60141 | ||
| wd2 | 8192 | 78342 | 76342 | |
| 16384 | 78311 | 75252 | ||
| netbsd-current/amd64 dom0 | wd0 | 8192 | 60641 | 60109 |
| 16384 | 60459 | 61919 | ||
| wd2 | 8192 | 80258 | 79102 | |
| 16384 | 80187 | 80295 | ||
| netbsd-current/amd64 domu | wd0 | 8192 | 51205 | 24004 |
| 16384 | 51714 | 27971 | ||
| wd2 | 8192 | 77990 | 23997 | |
| 16384 | 77282 | 22496 | ||
| netbsd-current/i386 domu | wd0 | 8192 | 41730 | 25012 |
| 16384 | 42008 | 24543 | ||
| wd2 | 8192 | 66401 | 26048 | |
| 16384 | 66201 | 28910 | ||
| netbsd-current/i386 vmware | wd0 | 8192 | 25014 | 13912 |
| 16384 | 25417 | 13771 | ||
| wd2 | 8192 | 38831 | 16100 | |
| 16384 | 38994 | 16332 |
I also repeated one test with a raw, physical partition mounted in the netbsd-current/amd64 domU, which bypasses the "double filesystem" issue:
| netbsd-current/amd64 domu | wd2 | 8192 | 79915 | 76992 |
| Physical mount | wd2 | 16384 | 79744 | 77102 |
CPU Performance
Each CPU speed test was run with: Dhrystone Benchmark, Version 2.1 (Language: C) Program compiled without 'register' attribute.
I used an iteration count of 1,000,000,000 for each test.
| Operating System | Dhrystones per second |
|---|---|
| netbsd-current/amd64 native | 11,013,216 |
| netbsd-current/amd64 dom0 | 10,365,917 |
| netbsd-current/amd64 domu | 11,130,899 |
| netbsd-current/i386 domu | 4,935,347 |
| netbsd-current/i386 vmware | 5,012,123 |
Just for grins, I ran the following tests, one dhrystone on one guest and another on a different one. Since each guest is uniprocessor in my configuration, I did not run two benchmarks on the same host.
| Operating Systems | Speed 1 | Speed 2 |
|---|---|---|
| Running both domu/i386 and domu/amd64 | 4916421.0 | 11135857.0 |
| Running both dom0/amd64 and domu/amd64 | 10298661.0 | 11135857.0 |
| Running both dom0/amd64 and domu/i386 | 10373444.0 | 4921260.0 |
Conclusions
Xen is production ready.
When the host OS can be modified, much higher performance numbers are obtained vs. the low-end VMware server I ran.
While it might be extremely tempting to build one guest that does one very specific function, this probably does not scale: memory is pre-allocated and dedicated to a guest, and while some swapping is allowed, it will slow the guest at seemingly random times; disk can be overcommitted, but the OS sees failure to allocate a block as a hardware failure; the more hosts, the more maintenance costs are present: maintaining packages on each guest, upgrading, etc.
VMware "hmx" or whatever the name of the run-on-bare-metal product should be tested.
I'd love to install Xen on a huge machine with lots of ram and many, many CPUs as a test. Would someone like to ship me a 4 CPU quad core with 64 GB?
Wednesday, April 23, 2008
Your cable company owns you
Well, ok, perhaps not entirely... yet.
This is actually a rant on something cable modems allow your cable internet provider to do to you.
They restrict access to your own hardware.
Why would they do this? Paranoia. A while back, there was a security hole in a network monitoring tool called Simple Network Management Protocol, or SNMP. This security issue allowed people to crash other people's modems, break into their own and change upload/download speeds, and other nasty things.
All of these have been fixed. However, people are still breaking into their modems to "uncap" them -- change speed settings. They just don't use SNMP to do it anymore. They've become more advanced and use things like internal serial ports or JTAG ports.
So, why do cable companies still restrict access to SNMP, and worse, to some of your modem's diagnostic features? I suspect it is because they don't want to have to answer questions about why they suck. They hide the real details of what your modem is doing from you.
Why is this a big deal?
For one, I own the hardware, but my cable company configures it against my wishes. I can understand rate limiting -- I pay for the fastest service already -- but I cannot understand restricting diagnostic tools.
For two, I have spent, in the last 6 months, perhaps 40 hours debugging a cable internet issue with techs from Cox Communications. After many, many rounds of techs who report "all signal levels are good" I finally got a real live network engineer on the line, who, in 5 minutes, could look at all the statistics on my modem. And solve problems.
Monday, March 24, 2008
Checking Credit Card Numbers in Ruby
This is not meant to be an exhaustive list of all possible numbers, nor the only or best method to verify that they pass the "checksum" test, but here's what I came up with.
I wrote this mostly to link a Ruby version of the code to Wikipedia's article on Luhn checksum validation, since nearly every other language in use was listed, but Ruby was sadly missing.
#!/usr/bin/env ruby
#
# Copyright (c) 2008 Michael Graff. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# 3. The name of Michael Graff may not be used to endorse or promote
# products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY Michael Graff ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Micahel Graff
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
# OF SUCH DAMAGE.
#
class Luhn
public
def self.check_luhn(s)
s.gsub!(/[^0-9]/, "")
ss = s.reverse.split(//)
alternate = false
total = 0
ss.each do |c|
if alternate
total += double_it(c.to_i)
else
total += c.to_i
end
alternate = !alternate
end
(total % 10) == 0
end
private
def self.double_it(i)
i = i * 2
if i > 9
i = i % 10 + 1
end
i
end
end
if $0 == __FILE__
def test_valid(s)
result = Luhn::check_luhn(s)
if result
puts "VALID: #{s}"
else
puts "INVALID: #{s} (should be valid)"
end
end
test_valid('5105 1051 0510 5100') # Mastercard
test_valid('5555 5555 5555 4444') # Mastercard
test_valid('4222 2222 2222 2') # Visa
test_valid('4111 1111 1111 1111') # Visa
test_valid('4012 8888 8888 1881') # Visa
test_valid('3782 8224 6310 005') # American Express
test_valid('3714 4963 5398 431') # American Express
test_valid('3787 3449 3671 000') # American Express Corporate
test_valid('3782 8224 6310 005') # Amex
test_valid('3400 0000 0000 009') # Amex
test_valid('3700 0000 0000 002') # Amex
test_valid('38520000023237') # Diners Club (14 digits)
test_valid('30569309025904') # Diners Club (14 digits)
test_valid('6011111111111117') # Discover (16 digits)
test_valid('6011 0000 0000 0004') # Discover
test_valid('6011 0000 0000 0012') # Discover
test_valid('6011000990139424') # Discover (16 digits)
test_valid('6011601160116611') # Discover (16 digits)
test_valid('3530111333300000') # JCB (16 digits)
test_valid('3566002020360505') # JCB (16 digits)
test_valid('5431111111111111') # Mastercard (16 digits)
end
Wednesday, March 19, 2008
Javascript application framework 'extjs' and privacy
Out of the box, extjs version 2.0.2 leaks privacy information.
If you fail to change the value of Ext.BLANK_IMAGE_URL to something local, it will default to http://extjs.com/s.gif. At first this might not seem bad, but remember that every time this image is fetched the referring URL is sent to the extjs.com web server.
At worse, this is a minor information link. Depending on what you might place in your URL line, this could be a major issue.
I have posted a comment on the extjs forums, but so far the developers don't see the problem. They say it is well documented in their FAQ, and that it is documented in the API docs.
I would prefer they opt for a warning message saying "You did not set ..." rather than leaking information by default. I'll probably have to post a CERT on this one.
Wednesday, October 31, 2007
Fun With Apache and Virtual Hosts
Specifically, name based virtual hosts.
I recently tried to add IPv6 support to my web server. I used to have it, I remember having it, so this should not be all that hard.
After an hour of hacking, I ended up finding two gotchas:
- Make certain, I mean certain, that all virtual hosts for name-based servers have a unique
ServerNameline. - Make certain, and I mean certain, to save your original configuration files.
A very useful tool is apachectl -S, which lists all virtual hosts. Even better is to run that output through sort.
Sunday, October 28, 2007
Mongrel, Apache, and Rails
When I first started running Rails applications on my web server, I chose to use FastCGI. Specifically, the mod_fcgid module, which had some features I wanted. It also has the unfortunate by-product of corrupting Apache's memory. Bad news.
I've since removed FastCGI entirely and moved to a proxy to mongrel_cluster setup. And I've started deploying with Capistrano.
Capistrano
I have a certain amount of concern with moving to a deployment system I knew very little about. Just like a new backup system, I feel like I'm handing the keys to my data over to something not written by me. And, while it is fairly simple to set up, Capistrano is somewhat complicated internally.
I already push out my operating system upgrades in an automated way. I compile NetBSD on one machine here at home, and push the binaries out to all my machines. This means about 7 machines rsync from the build box with one command. This can be scary, but I've been doing it for 5 years now, and it just works. How can a web site be scary compared to kernels and system binaries?
The answer is, it's not. If something breaks it is fairly easy to manually reconfigure if I need to. So, I've relaxed a bit. My concerns are still there, and I'm keeping a careful watch on how Capistrano runs each time I deploy. I have yet to do a *real* deployment after all! So far, I've not done a single migration, and have not had to roll back. And I'm pushing to a single machine, which runs the database as well as the site.
I suspect that, as I become comfortable with this new method to update my web sites, I'll start thinking of it as rsync++. It really is that simple.
mongrel_cluster
Mongrel is a vary amazing little widget. Sure, it's slower than Apache, but that's ok. Mongrel is still far, far faster than restarting Rails for each web hit, and far more reliable than mod_fcgid.
In my configuration, I run each site on ports 10000, 10010, 10020, etc. with up to 3 servers per. This means application #1 is on 10000 through 10002, with room to grow should I need to run more. If I find myself running more than 10 servers for a site it needs a new machine anyway, or more machines. And if that happens, I hope I'll have a budget.
Apache load balancing
This is a new feature in Apache 2.1, and apparently is very reliable with Apache 2.2. This is currently my favorite way to run a web site.
My configuration, which happens to be for this site:
<proxy balancer://blog>
BalancerMember http://localhost:10010
BalancerMember http://localhost:10011
BalancerMember http://localhost:10012
</proxy>
<VirtualHost blog.flame.org:80>
DocumentRoot /www/blog/flame-blog/current/public
<directory "/www/blog/flame-blog/current/public">
Options FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</directory>
ProxyRequests off
<proxy *>
order deny,allow
allow from all
</proxy>
RewriteEngine on
# Check for maintenance file. Let apache load it if it exists
RewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f
RewriteRule . /system/maintenance.html [L]
# Rewrite index to check for static
RewriteRule ^/$ balancer://blog%{REQUEST_URI} [L,P,QSA]
# Let apache serve static files (send everything via mod_proxy that
# is *no* static file (!-f)
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f
RewriteRule .* balancer://blog%{REQUEST_URI} [L,P,QSA]
</VirtualHost>
It is important, at least on my host, to use localhost in the balancer destinations. This is due to mongrel suddenly running on IPv6 loopback (::1) rather than the usual IPv4 loopback (127.0.0.1). I don't know why this happened, but the localhost trick makes Apache try both addresses, and whichever works it will use.
This configuration makes Apache serve static content, and sends all other requests off to one of the Mongrel processes.
Saturday, October 27, 2007
Ursae-Lyons
Last weekend my wife and I attended a lovely little event in the Barony of Bjornsborg in the Kingdom of Ansteorra. We had a wonderful time. There was music, a bardic circle, and lots of singing (most of it good!) coming from Cynric's tavern.
The best things to happen there, in my opinion, was that Baron Cynric of Bedwyn was awarded with the Kingdom's highest persona award, Lions of Ansteorra, Devenders of the Dream, and his lady wife Baroness Seraphina Maslowska was awarded with a Pelican! Congratulations to both of you!
RailsMode (not ENV['RAILS_ENV'])
I've been spreading things like this all around my code, where I wanted to do something differently in production vs. development mode. Previously, I'd write something like this:
if ENV['RAILS_ENV'] == 'production' # perform magic, in production mode ... end
While this is pretty simple, it just didn't feel very DRY. So, I decided to use this as a reason to learn about modules and mixins.
I have a generic plug-in in vendor/plugins that I put small bits of code like this. You might as well, but if you don't, you can drop this in a file in lib or in a helper.
module RailsMode
def railsmode(*list)
list.map! do |item|
item.to_s
end
if block_given?
if list.include?(ENV['RAILS_ENV'])
yield
end
else
return list.include?(ENV['RAILS_ENV'])
end
end
end
I also put this line in my environment.rb file:
include RailsMode
This mixes the module into the current class. Doing this in environment.rb makes it available everywhere in rails. Putting that line in a specific file would also work, such as a controller, or a helper.
With this, I can now write:
if railsmode(:production) # perform magic, in production mode ... end
I can also check for multiple modes at once:
if railsmode(:production, :development) # perform magic, in production or development ... end
And of course, who needs an if when I can pass in a block:
railsmode(:production) do # perform magic, in production mode ... end