1 (** Bitmatch library. *)
2 (* Copyright (C) 2008 Red Hat Inc., Richard W.M. Jones
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 * $Id: bitmatch.mli,v 1.13 2008-04-15 13:40:51 rjones Exp $
22 {{:#reference}Jump straight to the reference section for
23 documentation on types and functions}.
27 Bitmatch adds Erlang-style bitstrings and matching over bitstrings
28 as a syntax extension and library for OCaml. You can use
29 this module to both parse and generate binary formats, for
30 example, communications protocols, disk formats and binary files.
32 {{:http://et.redhat.com/~rjones/bitmatch/}OCaml bitmatch website}
36 A function which can parse IPv4 packets:
43 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
44 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
45 | 4 | IHL |Type of Service| Total Length |
46 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
47 | Identification |Flags| Fragment Offset |
48 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
49 | Time to Live | Protocol | Header Checksum |
50 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
52 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
53 | Destination Address |
54 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
56 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
58 | 4 : 4; hdrlen : 4; tos : 8; length : 16;
59 identification : 16; flags : 3; fragoffset : 13;
60 ttl : 8; protocol : 8; checksum : 16;
63 options : (hdrlen-5)*32 : bitstring;
64 payload : -1 : bitstring ->
67 printf " header length: %d * 32 bit words\n" hdrlen;
68 printf " type of service: %d\n" tos;
69 printf " packet length: %d bytes\n" length;
70 printf " identification: %d\n" identification;
71 printf " flags: %d\n" flags;
72 printf " fragment offset: %d\n" fragoffset;
73 printf " ttl: %d\n" ttl;
74 printf " protocol: %d\n" protocol;
75 printf " checksum: %d\n" checksum;
76 printf " source: %lx dest: %lx\n" source dest;
77 printf " header options + padding:\n";
78 Bitmatch.hexdump_bitstring stdout options;
79 printf " packet payload:\n";
80 Bitmatch.hexdump_bitstring stdout payload
83 eprintf "unknown IP version %d\n" version;
87 eprintf "data is smaller than one nibble:\n";
88 Bitmatch.hexdump_bitstring stderr pkt;
92 A program which can parse
93 {{:http://lxr.linux.no/linux/include/linux/ext3_fs.h}Linux EXT3 filesystem superblocks}:
96 let bits = Bitmatch.bitstring_of_file "tests/ext3_sb"
100 | s_inodes_count : 32 : littleendian; (* Inodes count *)
101 s_blocks_count : 32 : littleendian; (* Blocks count *)
102 s_r_blocks_count : 32 : littleendian; (* Reserved blocks count *)
103 s_free_blocks_count : 32 : littleendian; (* Free blocks count *)
104 s_free_inodes_count : 32 : littleendian; (* Free inodes count *)
105 s_first_data_block : 32 : littleendian; (* First Data Block *)
106 s_log_block_size : 32 : littleendian; (* Block size *)
107 s_log_frag_size : 32 : littleendian; (* Fragment size *)
108 s_blocks_per_group : 32 : littleendian; (* # Blocks per group *)
109 s_frags_per_group : 32 : littleendian; (* # Fragments per group *)
110 s_inodes_per_group : 32 : littleendian; (* # Inodes per group *)
111 s_mtime : 32 : littleendian; (* Mount time *)
112 s_wtime : 32 : littleendian; (* Write time *)
113 s_mnt_count : 16 : littleendian; (* Mount count *)
114 s_max_mnt_count : 16 : littleendian; (* Maximal mount count *)
115 0xef53 : 16 : littleendian -> (* Magic signature *)
117 printf "ext3 superblock:\n";
118 printf " s_inodes_count = %ld\n" s_inodes_count;
119 printf " s_blocks_count = %ld\n" s_blocks_count;
120 printf " s_free_inodes_count = %ld\n" s_free_inodes_count;
121 printf " s_free_blocks_count = %ld\n" s_free_blocks_count
124 eprintf "not an ext3 superblock!\n%!";
128 Constructing packets for a simple binary message
133 +---------------+---------------+--------------------------+
134 | type | subtype | parameter |
135 +---------------+---------------+--------------------------+
136 <-- 16 bits --> <-- 16 bits --> <------- 32 bits -------->
138 All fields are in network byte order.
141 let make_message typ subtype param =
148 {2 Loading, creating bitstrings}
150 The basic data type is the {!bitstring}, a string of bits of
151 arbitrary length. Bitstrings can be any length in bits and
152 operations do not need to be byte-aligned (although they will
153 generally be more efficient if they are byte-aligned).
155 Internally a bitstring is stored as a normal OCaml [string]
156 together with an offset and length, where the offset and length are
157 measured in bits. Thus one can efficiently form substrings of
158 bitstrings, overlay a bitstring on existing data, and load and save
159 bitstrings from files or other external sources.
161 To load a bitstring from a file use {!bitstring_of_file} or
162 {!bitstring_of_chan}.
164 There are also functions to create bitstrings from arbitrary data.
165 See the {{:#reference}reference} below.
167 {2 Matching bitstrings with patterns}
169 Use the [bitmatch] operator (part of the syntax extension) to break
170 apart a bitstring into its fields. [bitmatch] works a lot like the
171 OCaml [match] operator.
173 The general form of [bitmatch] is:
175 [bitmatch] {i bitstring-expression} [with]
177 [|] {i pattern} [->] {i code}
179 [|] {i pattern} [->] {i code}
183 As with normal match, the statement attempts to match the
184 bitstring against each pattern in turn. If none of the patterns
185 match then the standard library [Match_failure] exception is
188 Patterns look a bit different from normal match patterns. The
189 consist of a list of bitfields separated by [;] where each bitfield
190 contains a bind variable, the width (in bits) of the field, and
191 other information. Some example patterns:
196 | version : 8; name : 8; param : 8 -> ...
198 (* Bitstring of at least 3 bytes. First byte is the version
199 number, second byte is a field called name, third byte is
200 a field called parameter. *)
203 printf "flag is %b\n" flag
205 (* A single flag bit (mapped into an OCaml boolean). *)
207 | len : 4; data : 1+len ->
208 printf "len = %d, data = 0x%Lx\n" len data
210 (* A 4-bit length, followed by 1-16 bits of data, where the
211 length of the data is computed from len. *)
213 | ipv6_source : 128 : bitstring;
214 ipv6_dest : 128 : bitstring -> ...
216 (* IPv6 source and destination addresses. Each is 128 bits
217 and is mapped into a bitstring type which will be a substring
218 of the main bitstring expression. *)
221 You can also add conditional when-clauses:
225 when version = 4 || version = 6 -> ...
227 (* Only match and run the code when version is 4 or 6. If
228 it isn't we will drop through to the next case. *)
231 Note that the pattern is only compared against the first part of
232 the bitstring (there may be more data in the bitstring following
233 the pattern, which is not matched). In terms of regular
234 expressions you might say that the pattern matches [^pattern], not
235 [^pattern$]. To ensure that the bitstring contains only the
236 pattern, add a length -1 bitstring to the end and test that its
237 length is zero in the when-clause:
241 rest : -1 : bitstring
242 when Bitmatch.bitstring_length rest = 0 -> ...
244 (* Only matches exactly 4 bits. *)
247 Normally the first part of each field is a binding variable,
248 but you can also match a constant, as in:
253 (* Only matches if the first 4 bits contain the integer 6. *)
256 {3:patternfieldreference Pattern field reference}
258 The exact format of each pattern field is:
260 [pattern : length [: qualifier [,qualifier ...]]]
262 [pattern] is the pattern, binding variable name, or constant to
263 match. [length] is the length in bits which may be either a
264 constant or an expression. The length expression is just an OCaml
265 expression and can use any values defined in the program, and refer
266 back to earlier fields (but not to later fields).
268 Integers can only have lengths in the range \[1..64\] bits. See the
269 {{:#integertypes}integer types} section below for how these are
270 mapped to the OCaml int/int32/int64 types. This is checked
271 at compile time if the length expression is constant, otherwise it is
272 checked at runtime and you will get a runtime exception eg. in
273 the case of a computed length expression.
275 A bitstring field of length -1 matches all the rest of the
276 bitstring (thus this is only useful as the last field in a
279 A bitstring field of length 0 matches an empty bitstring
280 (occasionally useful when matching optional subfields).
282 Qualifiers are a list of identifiers which control the type,
283 signedness and endianness of the field. Permissible qualifiers are:
285 - [int] (field has an integer type)
286 - [bitstring] (field is a bitstring type)
287 - [signed] (field is signed)
288 - [unsigned] (field is unsigned)
289 - [bigendian] (field is big endian - a.k.a network byte order)
290 - [littleendian] (field is little endian - a.k.a Intel byte order)
291 - [nativeendian] (field is same endianness as the machine)
293 The default settings are [int], [unsigned], [bigendian].
295 Note that many of these qualifiers cannot be used together,
296 eg. bitstrings do not have endianness. The syntax extension should
297 give you a compile-time error if you use incompatible qualifiers.
299 {3 Other cases in bitmatch}
301 As well as a list of fields, it is possible to name the
302 bitstring and/or have a default match case:
307 (* Default match case. *)
311 (* Default match case, with 'pkt' bound to the whole bitstring. *)
314 {2 Constructing bitstrings}
316 Bitstrings may be constructed using the [BITSTRING] operator (as an
317 expression). The [BITSTRING] operator takes a list of fields,
318 similar to the list of fields for matching:
328 (* Constructs a 16-bit bitstring with the first four bits containing
329 the integer 1, and the following 12 bits containing the integer 10,
330 arranged in network byte order. *)
332 Bitmatch.hexdump_bitstring stdout bits ;;
340 The format of each field is the same as for pattern fields (see
341 {{:#patternfieldreference}Pattern field reference section}), and
342 things like computed length fields, fixed value fields, insertion
343 of bitstrings within bitstrings, etc. are all supported.
345 {3 Construction exception}
347 The [BITSTRING] operator may throw a {!Construct_failure}
348 exception at runtime.
350 Runtime errors include:
352 - int field length not in the range \[1..64\]
353 - a bitstring with a length declared which doesn't have the
354 same length at runtime
355 - trying to insert an out of range value into an int field
356 (eg. an unsigned int field which is 2 bits wide can only
357 take values in the range \[0..3\]).
359 {2:integertypes Integer types}
361 Integer types are mapped to OCaml types [bool], [int], [int32] or
362 [int64] using a system which tries to ensure that (a) the types are
363 reasonably predictable and (b) the most efficient type is
366 The rules are slightly different depending on whether the bit
367 length expression in the field is a compile-time constant or a
370 Detection of compile-time constants is quite simplistic so only an
371 immediate, simple integer is recognised as a constant and anything
372 else is considered a computed expression, even expressions such as
373 [5-2] which are obviously (to our eyes) constant.
375 In any case the bit size of an integer is limited to the range
376 \[1..64\]. This is detected as a compile-time error if that is
377 possible, otherwise a runtime check is added which can throw an
378 [Invalid_argument] exception.
383 Bit size ---- OCaml type ----
384 Constant Computed expression
392 A possible future extension may allow people with 64 bit computers
393 to specify a more optimal [int] type for bit sizes in the range
394 [32..63]. If this was implemented then such code {i could not even
395 be compiled} on 32 bit platforms, so it would limit portability.
397 Another future extension may be to allow computed
398 expressions to assert min/max range for the bit size,
399 allowing a more efficient data type than int64 to be
400 used. (Of course under such circumstances there would
401 still need to be a runtime check to enforce the
406 Using the compiler directly you can do:
409 ocamlc -I +bitmatch \
410 -pp "camlp4o `ocamlc -where`/bitmatch/pa_bitmatch.cmo" \
411 bitmatch.cma test.ml -o test
414 Simpler method using findlib:
418 -package bitmatch.syntax -syntax bitmatch.syntax \
419 -linkpkg test.ml -o test
422 {2 Security and type safety}
424 {3 Security on input}
426 The main concerns for input are buffer overflows and denial
429 It is believed that this library is robust against attempted buffer
430 overflows. In addition to OCaml's normal bounds checks, we check
431 that field lengths are >= 0, and many additional checks.
433 Denial of service attacks are more problematic although we still
434 believe that the library is robust. We only work forwards through
435 the bitstring, thus computation will eventually terminate. As for
436 computed lengths, code such as this is thought to be secure:
441 buffer : Int64.to_int len : bitstring ->
444 The [len] field can be set arbitrarily large by an attacker, but
445 when pattern-matching against the [buffer] field this merely causes
446 a test such as [if len <= remaining_size] to fail. Even if the
447 length is chosen so that [buffer] bitstring is allocated, the
448 allocation of sub-bitstrings is efficient and doesn't involve an
449 arbitary-sized allocation or any copying.
451 The main protection against attackers should therefore be to ensure
452 that the main program will only read input bitstrings up to a
453 certain length, which is outside the scope of this library.
455 {3 Security on output}
457 As with the input side, computed lengths are believed to be
461 let len = read_untrusted_source () in
462 let buffer = allocate_bitstring () in
464 buffer : len : bitstring
467 This code merely causes a check that buffer's length is the same as
468 [len]. However the program function [allocate_bitstring] must
469 refuse to allocate an oversized buffer (but that is outside the
470 scope of this library).
472 {3 Order of evaluation}
474 In [bitmatch] statements, fields are evaluated left to right.
476 Note that the when-clause is evaluated {i last}, so if you are
477 relying on the when-clause to filter cases then your code may do a
478 lot of extra and unncessary pattern-matching work on fields which
479 may never be needed just to evaluate the when-clause. You can
480 usually rearrange the code to do only the first part of the match,
481 followed by the when-clause, followed by a second inner bitmatch.
485 The current implementation is believed to be fully type-safe,
486 and makes compile and run-time checks where appropriate. If
487 you find a case where a check is missing please submit a
488 bug report or a patch.
492 These are thought to be the current limits:
494 Integers: \[1..64\] bits.
496 Bitstrings (32 bit platforms): maximum length is limited
497 by the string size, ie. 16 MBytes.
499 Bitstrings (64 bit platforms): maximum length is thought to be
500 limited by the string size, ie. effectively unlimited.
502 Bitstrings must be loaded into memory before we can match against
503 them. Thus available memory may be considered a limit for some
506 {2:reference Reference}
510 type bitstring = string * int * int
511 (** [bitstring] is the basic type used to store bitstrings.
513 The type contains the underlying data (a string),
514 the current bit offset within the string and the
515 current bit length of the string (counting from the
516 bit offset). Note that the offsets are bits, not bytes.
518 Normally you don't need to use the bitstring type
519 directly, since there are functions and syntax
520 extensions which hide the details.
521 See {!bitstring_of_file}, {!hexdump_bitstring},
525 (** {3 Exceptions} *)
527 exception Construct_failure of string * string * int * int
528 (** [Construct_failure (message, file, line, char)] may be
529 raised by the [BITSTRING] constructor.
531 Common reasons are that values are out of range of
532 the fields that contain them, or that computed lengths
533 are impossible (eg. negative length bitfields).
535 [message] is the error message.
537 [file], [line] and [char] point to the original source
538 location of the [BITSTRING] constructor that failed.
541 (** {3 Bitstrings} *)
543 val empty_bitstring : bitstring
544 (** [empty_bitstring] is the empty, zero-length bitstring. *)
546 val create_bitstring : int -> bitstring
547 (** [create_bitstring n] creates an [n] bit bitstring
548 containing all zeroes. *)
550 val make_bitstring : int -> char -> bitstring
551 (** [make_bitstring n c] creates an [n] bit bitstring
552 containing the repeated 8 bit pattern in [c].
554 For example, [make_bitstring 16 '\x5a'] will create
555 the bitstring [0x5a5a] or in binary [0101 1010 0101 1010].
557 Note that the length is in bits, not bytes. *)
559 val bitstring_of_chan : in_channel -> bitstring
560 (** [bitstring_of_chan chan] loads the contents of
561 the input channel [chan] as a bitstring.
563 The length of the final bitstring is determined
564 by the remaining input in [chan], but will always
565 be a multiple of 8 bits. *)
567 val bitstring_of_file : string -> bitstring
568 (** [bitstring_of_file filename] loads the named file
571 val hexdump_bitstring : out_channel -> bitstring -> unit
572 (** [hexdump_bitstring chan bitstring] prints the bitstring
573 to the output channel in a format similar to the
574 Unix command [hexdump -C]. *)
576 val bitstring_length : bitstring -> int
577 (** [bitstring_length bitstring] returns the length of
578 the bitstring in bits. *)
580 val string_of_bitstring : bitstring -> string
581 (** [string_of_bitstring bitstring] converts a bitstring to a string
582 (eg. to allow comparison).
584 This function is inefficient. In the best case when the bitstring
585 is nicely byte-aligned we do a [String.sub] operation. If the
586 bitstring isn't aligned then this involves a lot of bit twiddling
587 and is particularly inefficient.
589 XXX This function wouldn't be needed so much if the [bitmatch]
590 operator allowed us to pattern-match on strings. *)
592 (** {3 Bitstring buffer} *)
596 val create : unit -> t
597 val contents : t -> bitstring
598 val add_bits : t -> string -> int -> unit
599 val add_bit : t -> bool -> unit
600 val add_byte : t -> int -> unit
602 (** Buffers are mainly used by the [BITSTRING] constructor, but
603 may also be useful for end users. They work much like the
604 standard library [Buffer] module. *)
606 (** {3 Miscellaneous} *)
609 (** Set this variable to true to enable extended debugging.
610 This only works if debugging was also enabled in the
611 [pa_bitmatch.ml] file at compile time, otherwise it
616 (* Private functions, called from generated code. Do not use
617 * these directly - they are not safe.
620 val extract_bitstring : string -> int -> int -> int -> bitstring * int * int
622 val extract_remainder : string -> int -> int -> bitstring * int * int
624 val extract_bit : string -> int -> int -> int -> bool * int * int
626 val extract_char_unsigned : string -> int -> int -> int -> int * int * int
628 val extract_int_be_unsigned : string -> int -> int -> int -> int * int * int
630 val extract_int_le_unsigned : string -> int -> int -> int -> int * int * int
632 val extract_int32_be_unsigned : string -> int -> int -> int -> int32 * int * int
634 val extract_int32_le_unsigned : string -> int -> int -> int -> int32 * int * int
636 val extract_int64_be_unsigned : string -> int -> int -> int -> int64 * int * int
638 val construct_bit : Buffer.t -> bool -> int -> unit
640 val construct_char_unsigned : Buffer.t -> int -> int -> exn -> unit
642 val construct_int_be_unsigned : Buffer.t -> int -> int -> exn -> unit
644 val construct_int64_be_unsigned : Buffer.t -> int64 -> int -> exn -> unit