Debian Codegraph @

splitdns323fw

raw
1 #!/usr/bin/ruby
2
3 # Create and dismantle firmware files suitable for upload to a range of
4 # D-Link (and compatible) NAS devices.
5 #
6 # Copyright (C) 2008,2012,2014 Matt Palmer <[email protected]>
7 #
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 #
22 # This tool is based on information provided by Leschinsky Oleg. Many
23 # thanks go to him for deciphering (and publishing) his analysis of the file
24 # formats involved.
25 #
26 # This file should not be called as dns323fw-tool; create links to this file
27 # named 'mkdns323fw' and 'splitdns323fw'.
28
29 require 'optparse'
30
31 begin
32 require 'ffi'
33 rescue LoadError
34 $stderr.puts "The 'ffi' gem is not available."
35 $stderr.puts "Perhaps try running `gem install ffi`"
36 exit 1
37 end
38
39 # This class handles all the grunt work for decoding and encoding firmware
40 # files.
41 class DnsFirmware
42 # Represents a file which is a part of the firmware blob
43 class IncludedFile
44 # The contents of the file
45 attr_reader :contents
46
47 # The stored / calculated checksum
48 attr_reader :checksum
49
50 # This class can be instantiated in two different ways:
51 #
52 # * By passing in `:filename => "some file name"` as the second
53 # argument; or
54 #
55 # * By passing in `:contents => "some file contents"` and `:checksum
56 # => <number>` as the second argument.
57 #
58 def initialize(opts)
59 if opts[:filename] and (opts[:contents] or opts[:checksum])
60 raise ArgumentError,
61 "Must pass either :filename or :contents and :checksum to #{self.class}.initialize"
62 end
63
64 if opts[:filename]
65 @filename = File.expand_path(opts[:filename])
66 @contents = File.read(@filename).force_encoding("BINARY")
67 elsif opts[:contents]
68 @contents = opts[:contents]
69 if opts[:checksum]
70 @checksum = opts[:checksum]
71 end
72 else
73 raise ArgumentError,
74 "Must pass exactly one of :filename or :contents to #{self.class}.initialize"
75 end
76
77 # Calculate a checksum if one was not provided
78 @checksum ||= calculate_checksum
79 end
80
81 def validate
82 if @filename and !File.exists?(@filename)
83 log_error "does not exist"
84 end
85
86 unless @checksum == self.calculate_checksum
87 $stderr.puts "Checksum of #{type} file is incorrect (expected #{@checksum}, got #{checksum(@contents)}"
88 end
89
90 true
91 end
92
93 def log_error(s)
94 if @filename
95 $stderr.print "#{@filename}: "
96 end
97 $stderr.puts s
98 end
99
100 def size
101 @contents.length
102 end
103
104 def calculate_checksum
105 @contents.unpack("V*").inject(0) { |v, i| v ^= i }
106 end
107
108 def write(f)
109 File.write(f, @contents)
110 end
111 end
112
113 # Any included file that should be a uBoot file
114 class UBootFile < IncludedFile
115 def validate
116 super or return false
117
118 unless @contents[0..3] == "\x27\x05\x19\x56"
119 $stderr.puts "#{type} file #{@filename} does not appear to be a uBoot image file"
120 return false
121 end
122
123 true
124 end
125 end
126
127 class KernelFile < UBootFile
128 def type
129 :kernel
130 end
131 end
132
133 class InitrdFile < UBootFile
134 def type
135 :initrd
136 end
137 end
138
139 class DefaultsFile < IncludedFile
140 def type
141 :defaults
142 end
143
144 def validate
145 super or return false
146
147 unless @contents[0..1] == "\x1f\x8b"
148 $stderr.puts "defaults file does not appear to be gzipped"
149 return false
150 end
151
152 true
153 end
154 end
155
156 class SquashfsFile < IncludedFile
157 def type
158 :squashfs
159 end
160
161 def validate
162 super or return false
163
164 unless @contents[0x800..0x803] == "hsqs" or
165 @contents[0x800..0x803] == "shsq"
166 $stderr.puts "filesystem image file does not appear to be a squashfs filesystem"
167 return false
168 end
169
170 true
171 end
172 end
173
174 class GenericHeader < FFI::Struct
175 def initialize(content = nil)
176 super()
177
178 if content
179 if content.length != self.size
180 raise ArgumentError,
181 "Content passed to #{self.class}.new must be #{self.size} bytes"
182 end
183 self.to_ptr.write_string(content)
184 end
185 end
186
187 def data
188 self.to_ptr.read_string(self.size)
189 end
190 end
191
192 class FrodoHeader < GenericHeader
193 layout :kernel_offset, :uint32, # 0
194 :kernel_size, :uint32, # 4
195 :initrd_offset, :uint32, # 8
196 :initrd_size, :uint32, # 12
197 :defaults_offset, :uint32, # 16
198 :defaults_size, :uint32, # 20
199 :kernel_sum, :uint32, # 24
200 :initrd_sum, :uint32, # 28
201 :defaults_sum, :uint32, # 32
202 :magic1, [:uint8, 2], # 36
203 :sig, [:uint8, 8], # 38
204 :magic2, [:uint8, 2], # 46
205 :product_id, :uint8, # 48
206 :custom_id, :uint8, # 49
207 :model_id, :uint8, # 50
208 :compat_flag, :uint8, # 51
209 :compat_id, :uint8, # 52
210 :_1, [:uint8, 11] # 53
211
212 def signature
213 self[:sig].to_ptr.read_string.strip
214 end
215
216 def signature=(s)
217 if s.length > 8
218 raise ArgumentError,
219 "Signature can be no more than 8 bytes"
220 end
221 self[:sig].to_ptr.write_string(s)
222 end
223
224 def valid?
225 self[:magic1].to_s == "\x55\xAA".force_encoding("BINARY") and
226 self[:magic2].to_s == "\x55\xAA".force_encoding("BINARY")
227 end
228 end
229
230 class LongHeader < GenericHeader
231 layout :kernel_offset, :uint32, # 0
232 :kernel_size, :uint32, # 4
233 :initrd_offset, :uint32, # 8
234 :initrd_size, :uint32, # 12
235 :squashfs_offset, :uint32, # 16
236 :squashfs_size, :uint32, # 20
237 :defaults_offset, :uint32, # 24
238 :defaults_size, :uint32, # 28
239 :kernel_sum, :uint32, # 32
240 :initrd_sum, :uint32, # 36
241 :squashfs_sum, :uint32, # 40
242 :defaults_sum, :uint32, # 44
243 :magic1, [:uint8, 2], # 48
244 :sig, [:uint8, 8], # 50
245 :magic2, [:uint8, 2], # 58
246 :product_id, :uint8, # 60
247 :custom_id, :uint8, # 61
248 :model_id, :uint8, # 62
249 :compat_flag, :uint8, # 63
250 :compat_id, :uint8, # 64
251 :_1, [:uint8, 63] # 65
252
253 def signature
254 self[:sig].to_ptr.read_string.strip
255 end
256
257 def signature=(s)
258 if s.length > 8
259 raise ArgumentError,
260 "Signature can be no more than 8 bytes"
261 end
262 self[:sig].to_ptr.write_string(s)
263 end
264
265 def valid?
266 self[:magic1].to_s == "\x55\xAA".force_encoding("BINARY") and
267 self[:magic2].to_s == "\x55\xAA".force_encoding("BINARY")
268 end
269 end
270
271 HEADER_FORMATS = [FrodoHeader, LongHeader]
272
273 # This class can be initialized two ways:
274 #
275 # - with a single string argument, which is the filename of an existing
276 # firmware file to be dissected; or
277 #
278 # - with a hash containing the following keys:
279 # * `:kernel_file` (required) -- A file containing a raw bzImage kernel
280 #
281 # * `:initrd_file` (required) -- A file containing an initrd
282 #
283 # * `:defaults_file` (optional) -- A file containing a compressed
284 # tarball of configuration data; take a look at an existing
285 # firmware file for your device to see what can be in there.
286 #
287 # * `:squashfs_file` (optional) -- A file containing a squashfs
288 # filesystem image. Only some newer devices (DNS-320, etc)
289 # make use of such a file.
290 #
291 # * `:product_id` (required) -- The "product ID" to embed in the
292 # firmware file. What this needs to be set to is entirely
293 # dependent on your device and what it expects. It *appears*
294 # that hardware that is substantially identical will tend to
295 # share a common product ID, even if it is badged differently.
296 #
297 # * `:custom_id` (required) -- The "customisation ID" to embed in the
298 # firmware file. What this needs to be set to is entirely
299 # dependent on your device and what it expects. It appears that
300 # hardware that is substantially identical, but shipped by
301 # different vendors, will usually have a different custom ID.
302 #
303 # * `:model_id` (required) -- The "model ID" to embed in the firmware
304 # file. What this needs to be set to is entirely dependent on
305 # your device and what it expects.
306 #
307 # * `:compat_id` (optional) -- The "compatibility version ID" to embed
308 # in the firmware file. As far as can be determined, some
309 # firmware loaders will not load a firmware file which contains a
310 # compatibility ID lower than an arbitrary figure.
311 #
312 # * `:signature` (required) -- The signature to embed in the firmware
313 # file. This is some sort of magic string that lets the firmware
314 # loader know that its reading a real firmware file, as opposed
315 # to some random gibberish. What you need to set this to is
316 # determined entirely by what your device expects to see. The
317 # signature is also used to determine what kind of header to place
318 # in front of the firmware.
319 #
320 def initialize(opts)
321 @files = {}
322
323 if opts.is_a? String
324 @firmware_file = opts
325
326 candidate_formats = HEADER_FORMATS.select do |hf|
327 h = hf.new(File.read(@firmware_file, hf.size))
328 h.valid?
329 end
330
331 if candidate_formats.empty?
332 $stderr.puts "Unable to recognise the format of firmware file #{@firmware_file}"
333 $stderr.puts "The file may be corrupted, or this firmware may be a format I am not familiar with."
334 exit 1
335 end
336
337 if candidate_formats.length > 1
338 $stderr.puts "This firmware is of an ambiguous format."
339 $stderr.puts "Please inform [email protected], and include a"
340 $stderr.puts "link to the firmware file for testing."
341 exit 1
342 end
343
344 @header = candidate_formats.first.new(File.read(@firmware_file, candidate_formats.first.size))
345
346 @files[:kernel] = KernelFile.new(
347 :contents => File.read(
348 @firmware_file,
349 @header[:kernel_size],
350 @header[:kernel_offset]
351 ),
352 :checksum => @header[:kernel_sum]
353 )
354 @files[:initrd] = InitrdFile.new(
355 :contents => File.read(
356 @firmware_file,
357 @header[:initrd_size],
358 @header[:initrd_offset]
359 ),
360 :checksum => @header[:initrd_sum]
361 )
362 if @header[:defaults_size] > 0
363 @files[:defaults] = DefaultsFile.new(
364 :contents => File.read(
365 @firmware_file,
366 @header[:defaults_size],
367 @header[:defaults_offset]
368 ),
369 :checksum => @header[:defaults_sum]
370 )
371 end
372 if @header.members.include?(:squashfs_size) and @header[:squashfs_size] > 0
373 @files[:squashfs] = SquashfsFile.new(
374 :contents => File.read(
375 @firmware_file,
376 @header[:squashfs_size],
377 @header[:squashfs_offset]
378 ),
379 :checksum => @header[:squashfs_sum]
380 )
381 end
382 elsif opts.is_a? Hash
383 [:kernel_file, :initrd_file].each do |f|
384 unless opts[f]
385 raise ArgumentError,
386 "No #{f.inspect} provided"
387 end
388 end
389
390 @files[:kernel] = KernelFile.new(:filename => opts[:kernel_file])
391 @files[:initrd] = InitrdFile.new(:filename => opts[:initrd_file])
392 if opts[:defaults_file]
393 @files[:defaults] = DefaultsFile.new(:filename => opts[:defaults_file])
394 end
395 if opts[:squashfs_file]
396 @files[:squashfs] = SquashfsFile.new(:filename => opts[:squashfs_file])
397 end
398
399 @product_id = opts[:product_id] or raise ArgumentError.new("No :product_id provided")
400 @custom_id = opts[:custom_id] or raise ArgumentError.new("No :custom_id provided")
401 @model_id = opts[:model_id] or raise ArgumentError.new("No :model_id provided")
402 @compat_id = opts[:compat_id]
403 @signature = opts[:signature] or raise ArgumentError.new("No :signature provided")
404
405 # This logic will probably have to be improved somewhat, likely via
406 # another option, in the future
407 if @signature =~ /^DNS32/
408 @header = LongHeader.new
409 else
410 @header = FrodoHeader.new
411 end
412
413 @header[:magic1] = @header[:magic2] = "\x55\xAA"
414 else
415 raise ArgumentError.new("Incorrect type passed to DnsFirmware#initialize. String or Hash expected, got #{opts.class}")
416 end
417 end
418
419 def product_id
420 @header[:product_id]
421 end
422
423 def custom_id
424 @header[:custom_id]
425 end
426
427 def model_id
428 @header[:model_id]
429 end
430
431 def compat_id
432 @header[:compat_flag] ? @header[:compat_id] : nil
433 end
434
435 def kernel
436 @files[:kernel]
437 end
438
439 def initrd
440 @files[:initrd]
441 end
442
443 def defaults
444 @files[:defaults]
445 end
446
447 def squashfs
448 @files[:squashfs]
449 end
450
451 # Return the signature of this firmware file.
452 def signature
453 @header.signature
454 end
455
456 # This method works from the kernel/initrd/defaults/etc data and writes out
457 # a complete firmware file to the destfile of your choosing.
458 def write_firmware_file(destfile)
459 @header.signature = @signature
460 @header[:product_id] = @product_id
461 @header[:custom_id] = @custom_id
462 @header[:model_id] = @model_id
463 @header[:compat_flag] = @compat_id.nil? ? 0 : 1
464 @header[:compat_id] = @compat_id.to_i
465
466 file_offset = @header.size
467 file_types = @header.
468 members.
469 grep(/_sum$/).
470 map { |m| m.to_s.sub(/_sum$/, '').to_sym }
471
472
473 file_types.each do |f_type|
474 @header["#{f_type}_offset".to_sym] = file_offset
475 if @files[f_type]
476 @header["#{f_type}_size".to_sym] = @files[f_type].size
477 @header["#{f_type}_sum".to_sym] = @files[f_type].checksum
478 file_offset += @files[f_type].size
479 else
480 @header["#{f_type}_size".to_sym] = 0
481 @header["#{f_type}_sum".to_sym] = 0
482 end
483 end
484
485 File.open(destfile, 'w') do |fd|
486 fd.write @header.data
487
488 file_types.each do |f_type|
489 fd.write @files[f_type].contents if @files[f_type]
490 end
491 end
492 end
493
494 def validate
495 @files.values.each { |f| f.validate }
496 end
497 end
498
499 def mkdns323fw(args)
500 devices = {
501 'DNS-325' => {
502 :signature => 'DNS-325',
503 :product_id => 0,
504 :custom_id => 8,
505 :model_id => 5
506 },
507 'DNS-323' => {
508 :signature => 'FrodoII',
509 :product_id => 7,
510 :custom_id => 1,
511 :model_id => 1
512 },
513 'DNS-321' => {
514 :signature => 'Chopper',
515 :product_id => 10,
516 :custom_id => 1,
517 :model_id => 1
518 },
519 'DNS-320' => {
520 :signature => 'DNS323D1', # No, seriously...
521 :product_id => 0,
522 :custom_id => 8,
523 :model_id => 7
524 },
525 'DNS-320B' => {
526 :signature => 'DNS320B',
527 :product_id => 0,
528 :custom_id => 8,
529 :model_id => 12
530 },
531 'DNS-320L' => {
532 :signature => 'DNS320L',
533 :product_id => 0,
534 :custom_id => 8,
535 :model_id => 11
536 },
537 'CH3SNAS' => {
538 :signature => 'FrodoII',
539 :product_id => 7,
540 :custom_id => 2,
541 :model_id => 1
542 },
543 }
544
545 opts = OptionParser.new
546 optargs = {}
547
548 opts.on('-h', '--help',
549 "Print this help") { puts opts.to_s; exit 0 }
550 opts.on('-k KERNEL', '--kernel KERNEL',
551 "Specify the kernel to include in the firmware image",
552 String) { |k| optargs[:kernel_file] = k }
553 opts.on('-i INITRD', '--initrd INITRD',
554 "Specify the initrd to include in the firmware image",
555 String) { |i| optargs[:initrd_file] = i }
556 opts.on('-d DEFAULTS', '--defaults DEFAULTS',
557 "Specify the defaults.tar.gz to include in the firmware image (optional)",
558 String) { |d| optargs[:defaults_file] = d }
559 opts.on('--squashfs SQUASHFS',
560 "Specify a squashfs filesystem image to include in the firmware image (optional)",
561 String) { |d| optargs[:squashfs_file] = d }
562 opts.on('-o OUTPUT', '--output OUTPUT',
563 "Specify where to put the resulting firmware image",
564 String) { |o| optargs[:output] = o }
565 opts.on('-p PROD_ID', '--product-id PROD_ID',
566 "The product ID to embed in the firmware image",
567 Integer) { |p| optargs[:product_id] = p }
568 opts.on('-c CUSTOM_ID', '--custom-id CUSTOM_ID',
569 "The custom ID to embed in the firmware image",
570 Integer) { |c| optargs[:custom_id] = c }
571 opts.on('-m MODEL_ID', '--model-id MODEL_ID',
572 "The model ID to embed in the firmware image",
573 Integer) { |m| optargs[:model_id] = m }
574 opts.on('-s SIGNATURE', '--signature SIGNATURE',
575 "The firmware signature type",
576 String) { |s| optargs[:signature] = s }
577 opts.on('-t DEVICE', '--device-type DEVICE',
578 "Specify all the IDs and signature by choosing a device",
579 "Known devices: #{devices.keys.join(' ')}",
580 String) { |s| optargs[:device] = s }
581
582 opts.parse(args)
583
584 if optargs[:device]
585 optargs.merge!(devices[optargs.delete(:device)])
586 end
587
588 opts = optargs
589
590 %w{kernel_file initrd_file output product_id custom_id model_id}.each do |k|
591 if opts[k.to_sym].nil?
592 $stderr.puts "Missing required argument #{k}"
593 exit 1
594 end
595 end
596
597 opts[:signature] ||= "FrodoII"
598
599 # We just hardwire this to be the maximum value for now, since there is
600 # no indication that it does any harm in the wild
601 opts[:compat_id] = 255
602
603 begin
604 fw = DnsFirmware.new(opts)
605 fw.validate and fw.write_firmware_file(opts[:output])
606 rescue StandardError => e
607 $stderr.puts "Firmware generation failed: #{e.class}: #{e.message}"
608 e.backtrace.each { |l| puts " #{l}" }
609 else
610 puts "Firmware generation completed successfully."
611 end
612 end
613
614 def splitdns323fw(args)
615 opts = OptionParser.new
616 optargs = {}
617
618 opts.on('-h', '--help',
619 "Print this help") { $stderr.puts opts.to_s; exit 0 }
620 opts.on('-k KERNEL', '--kernel KERNEL',
621 "Write out the kernel to the specified file",
622 String) { |k| optargs[:kernel] = k }
623 opts.on('-i INITRD', '--initrd INITRD',
624 "Write out the initrd to the specified file",
625 String) { |i| optargs[:initrd] = i }
626 opts.on('-d DEFAULTS', '--defaults DEFAULTS',
627 "Write out the defaults.tar.gz to the specified file",
628 String) { |d| optargs[:defaults] = d }
629 opts.on('-s SQUASHFS', '--squashfs SQUASHFS',
630 "Write out the squashfs filesystem image to the specified file",
631 String) { |s| optargs[:squashfs] = s }
632
633 image = opts.parse(args)
634
635 if image.nil? or image.empty?
636 $stderr.puts "No firmware image provided!"
637 exit 1
638 end
639
640 if image.length > 1
641 $stderr.puts "I can only read one firmware image!"
642 exit 1
643 end
644
645 image = image[0]
646
647 fw = DnsFirmware.new(image)
648
649 puts "'#{fw.signature}' firmware signature found"
650
651 fw.kernel.validate or $stderr.puts "Kernel data failed validation"
652 puts "Kernel is #{fw.kernel.size} bytes"
653 fw.initrd.validate or $stderr.puts "Initrd data failed validation"
654 puts "initrd is #{fw.initrd.size} bytes"
655 if fw.defaults
656 fw.defaults.validate or $stderr.puts "Defaults data failed validation"
657 puts "defaults.tar.gz is #{fw.defaults.size} bytes"
658 else
659 puts "No defaults.tar.gz in this firmware file"
660 end
661
662 if fw.squashfs
663 fw.squashfs.validate or $stderr.puts "squashfs data failed validation"
664 puts "squashfs is #{fw.squashfs.size} bytes"
665 else
666 puts "No squashfs in this firmware file"
667 end
668
669 puts "Product ID: #{fw.product_id}"
670 puts "Custom ID: #{fw.custom_id}"
671 puts "Model ID: #{fw.model_id}"
672 puts "Compat ID: #{fw.compat_id}"
673
674 if optargs[:kernel]
675 fw.kernel.write(optargs[:kernel])
676 puts "Kernel data written to #{optargs[:kernel]}"
677 end
678
679 if optargs[:initrd]
680 fw.initrd.write(optargs[:initrd])
681 puts "initrd data written to #{optargs[:initrd]}"
682 end
683
684 if optargs[:defaults]
685 if fw.defaults
686 fw.defaults.write(optargs[:defaults])
687 puts "defaults.tar.gz written to #{optargs[:defaults]}"
688 else
689 $stderr.puts "This firmware file does not have a defaults.tar.gz; not written"
690 end
691 end
692
693 if optargs[:squashfs]
694 if fw.squashfs
695 fw.squashfs.write(optargs[:squashfs])
696 puts "squashfs filesystem image written to #{optargs[:squashfs]}"
697 else
698 $stderr.puts "This firmware file does not have a squashfs filesystem image; not written"
699 end
700 end
701 end
702
703 if $0 == __FILE__
704 case File.basename($0)
705 when 'mkdns323fw' then mkdns323fw(ARGV)
706 when 'splitdns323fw' then splitdns323fw(ARGV)
707 else
708 $stderr.puts "Please call me as either 'mkdns323fw' or 'splitdns323fw'; symlinks are good"
709 exit 1
710 end
711 end