]> git.cryptolib.org Git - arm-crypto-lib.git/blob - host/rsassa_pkcs1v15_check.rb
fixing bugs reported by Christian Dernehl
[arm-crypto-lib.git] / host / rsassa_pkcs1v15_check.rb
1 #!/usr/bin/ruby
2 # rsassa_pkcs1v15_check.rb
3 =begin
4     This file is part of the AVR-Crypto-Lib.
5     Copyright (C) 2012  Daniel Otte (daniel.otte@rub.de)
6
7     This program is free software: you can redistribute it and/or modify
8     it under the terms of the GNU General Public License as published by
9     the Free Software Foundation, either version 3 of the License, or
10     (at your option) any later version.
11
12     This program is distributed in the hope that it will be useful,
13     but WITHOUT ANY WARRANTY; without even the implied warranty of
14     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15     GNU General Public License for more details.
16
17     You should have received a copy of the GNU General Public License
18     along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 =end
20
21 require 'rubygems'
22 require 'serialport'
23 require 'getopt/std'
24 require 'fileutils'
25
26 $buffer_size = 0 # set automatically in init_system
27 $conffile_check = Hash.new
28 $conffile_check.default = 0
29 $debug = false
30 $progress_dots = false
31 $logfile = nil
32
33 ################################################################################
34 # readconfigfile                                                               #
35 ################################################################################
36
37 def read_line_from_device()
38   repeat_counter = 10000
39   l = nil
40   s = ''
41   begin
42     l = $sp.gets()
43     repeat_counter -= 1
44   end while !l && repeat_counter > 0
45   t = Time.new
46   $logfile.printf("DBG: (%02d:%02d:%02d)<< %s\n", t.hour, t.min, t.sec, l.inspect) if $debug
47   if l && l.include?("AVR-Crypto-Lib")
48     $logfile.printf("DBG: system crashed !!!\n")
49     exit(false)
50   end
51   return l
52 end
53
54 def readconfigfile(fname, conf)
55   return conf if $conffile_check[fname]==1
56   $conffile_check[fname]=1
57   section = "default"
58   if not File.exists?(fname)
59     return conf
60   end
61   file = File.open(fname, "r")
62   until file.eof
63     line = file.gets()
64           next if /[\s]*#/.match(line)
65         if m=/\[[\s]*([^\s]*)[\s]*\]/.match(line)
66             section=m[1]
67             conf[m[1]] = Hash.new
68             next
69           end
70           next if ! /=/.match(line)
71           m=/[\s]*([^\s]*)[\s]*=[\s]*([^\s]*)/.match(line)
72           if m[1]=="include"
73             Dir.glob(m[2]){ |fn| conf = readconfigfile(fn, conf) }
74           else
75           conf[section][m[1]] = m[2]
76           end
77   end
78   file.close()
79   return conf
80 end
81
82 ################################################################################
83 # reset_system                                                                 #
84 ################################################################################
85
86 def reset_system
87   $sp.print("\r")
88   sleep 0.1
89   $sp.print("\r")
90   sleep 0.1
91   $sp.print("echo off\r")
92   sleep 0.1
93 end
94
95
96 def read_block(f)
97   d = Array.new
98   begin
99     v = false
100     l = f.gets
101  #   x = l.split.collect { |e| e.to_i(16) }
102     t = l.split
103     t.each { |e| v = true if e.length != 2 }
104     x = []
105     x = t.collect { |e| e.to_i(16) } if ! v
106     d += x
107   end while x.length == 16 && ! v
108   return d
109 end
110
111 =begin
112 # Modulus: 
113 # Exponent: 
114 # Modulus: 
115 # Public exponent: 
116 # Exponent: 
117 # Prime 1: 
118 # Prime 2: 
119 # Prime exponent 1: 
120 # Prime exponent 2: 
121 # Coefficient: 
122 # Message:
123 # Seed:
124 # Encryption:
125
126 =end
127
128 def get_next_block(f)
129   ret = Hash.new
130   data = Array.new
131   begin
132     l = f.gets
133   end while l && ! m= l.match(/^#[\s](.*):[\s]*$/)
134   return nil if ! l
135   ret['tag'] = m[1]
136   ret['line'] = f.lineno
137   data = read_block(f)
138   ret['data'] = data
139   return ret
140 end
141
142 $key_sequence = [
143   'Modulus',             # 0
144   'Exponent',            # 1
145   'Modulus',             # 2
146   'Public exponent',     # 3
147   'Exponent',            # 4
148   'Prime 1',             # 5
149   'Prime 2',             # 6
150   'Prime exponent 1',    # 7
151   'Prime exponent 2',    # 8
152   'Coefficient',         # 9
153 ]
154
155 def key_consitency_check(k)
156   return true
157 end
158
159 def process_file(f, skip_key=1, skip_vec=1)
160   a = get_next_block(f)
161   key_no = 0
162   ok_counter = 0
163   fail_counter = 0
164   begin
165     if !a || ! a['tag'] == 'Modulus'
166       printf("ERROR: a = %s %d\n", a.inspect, __LINE__)
167       return
168     end
169     k_seq = Array.new
170     k_seq[0] = a
171     (1..($key_sequence.length-1)).each do |i|
172       a = get_next_block(f)
173       if ! a || a['tag'] != $key_sequence[i]
174         printf("ERROR: (expecting: %s) a = %s %d\n", $key_sequence[i], a.inspect, __LINE__)
175       end
176       k_seq[i] = a
177     end
178     key = convert_key(k_seq)
179     printf("ERROR: %d\n", __LINE__) if ! key
180     key_no += 1
181     vec_no = 0
182     printf("\n run %3d: ", key_no)
183     skip_key_flag = (key_no < skip_key)
184     load_key(key) if ! skip_key_flag
185     test_seq = Array.new
186     a = get_next_block(f)
187     printf("ERROR: %d\n", __LINE__) if ! a 
188     begin
189       vec_no += 1
190       b = get_next_block(f)
191       tv = Hash.new
192       tv['msg'] = a['data']
193       tv['sign'] = b['data'] 
194       skip_vec_flag = (skip_key_flag || (key_no == skip_key && vec_no < skip_vec))
195       if skip_vec_flag
196         printf('o')
197       else
198         v = check_tv(tv)
199         if(v == true)
200           printf('*')
201           $logfile.printf("[[Test %2d.%02d = OK]]\n", key_no, vec_no)
202           ok_counter += 1
203         else
204           printf('%c', v ? '*' : '!')
205           $logfile.printf("[[Test %2d.%02d = FAIL]]\n", key_no, vec_no)
206           fail_counter += 1
207         end
208       end
209       a = get_next_block(f)
210     end while a && a['tag'] == 'Message to be signed'
211   end while a && a['tag'] = 'Modulus'
212 #  printf("\nResult: %d OK / %d FAIL ==> %s \nFinished\n", ok_counter, fail_counter, fail_counter==0 ? ':-)' : ':-(')
213   return ok_counter,fail_counter
214 end
215
216 def convert_key(k_seq)
217   l = ['n', 'e', 'd', 'p', 'q', 'dP', 'dQ', 'qInv']
218   r = Hash.new
219   return nil if k_seq[0]['data'] != k_seq[2]['data']
220   return nil if k_seq[1]['data'] != k_seq[3]['data']
221   8.times do |i|
222     r[l[i]] = k_seq[2 + i]['data'] 
223   end
224   return r
225 end
226
227 def wait_for_dot
228   begin
229     s = $sp.gets()
230   end while !s || !s.include?('.')
231 end
232
233 def load_bigint(d)
234   $sp.printf("%d\r", d.length)
235   while l = read_line_from_device()
236     break if /data:/.match(l)
237   end
238   printf "ERROR: got no answer from system!" if !l
239   i = 0
240   d.each do |e|
241     $sp.printf("%02x", e)
242     i += 1
243     if i % 60 == 0
244 # we should now wait for incomming dot
245       wait_for_dot()
246       print('.') if $progress_dots
247     end
248   end
249 end
250
251 def hexdump(a)
252   i = 0
253   a.each do |e|
254     printf("\n\t") if i % 16 == 0
255     printf('%02x ', e)
256     i += 1
257   end
258   puts('') if i % 16 != 1
259 end
260
261 def str_hexdump(a)
262   i = 0
263   s = ''
264   a.each do |e|
265     s += "\n\t" if i % 16 == 0
266     s += sprintf('%02x ', e)
267     i += 1
268   end
269   s += "\n" if i % 16 != 1
270   return s
271 end
272
273 def load_key(k)
274   $sp.print("load-key\r")
275   sleep 0.1
276   v = ['n', 'e', 'p', 'q', 'dP', 'dQ', 'qInv']  
277   v.each do |e|
278     load_bigint(k[e])
279     $logfile.printf("DBG: loaded %s\n", e) if $debug
280   end 
281   while l = read_line_from_device()
282     break if />/.match(l)
283   end
284 end
285
286 def strip_leading_zeros(a)
287   loop do
288     return [] if a.length == 0
289     return a if a[0] != 0
290     a.delete_at(0)
291   end
292 end
293
294 def check_tv(tv)
295   sleep 0.1
296   $sp.print("sha1-test\r")
297   sleep 0.1
298   load_bigint(tv['msg'])
299   $logfile.printf("DBG: loaded %s\n", 'msg') if $debug
300   sleep 0.1
301   while l = read_line_from_device() 
302     break if /signature:/.match(l)
303   end
304   test_sign = ''
305   loop do 
306     l = read_line_from_device()
307     t = l.split
308     v = false
309     t.each { |e| v = true if e.length != 2 }
310     x = t.collect { |e| e.to_i(16) }
311     break if v
312     test_sign += l if l
313   end
314   test_sign_a = Array.new
315   test_sign = test_sign.split(/[\W\r\n]+/)
316   test_sign.each do |e|
317     v = e.sub(/[^0-9A-Fa-f]/, '') 
318     test_sign_a << v if v.length == 2
319   end
320   test_sign_a.collect!{ |e| e.to_i(16) }
321   strip_leading_zeros(test_sign_a)
322   strip_leading_zeros(tv['sign'])
323   sign_ok = (test_sign_a == tv['sign'])
324   if !sign_ok
325     $logfile.printf("DBG: ref = %s test = %s\n", str_hexdump(tv['sign']) , str_hexdump(test_sign_a))
326   end
327   m = nil
328   loop do 
329     l = read_line_from_device() 
330     m = /(>>OK<<|ERROR)/.match(l)
331     break if m
332   end
333   return true if sign_ok && (m[1] == '>>OK<<') 
334   return false
335 end
336
337 ########################################
338 # MAIN
339 ########################################
340 help_text = <<EOF
341 Usage of 'rsassa_pkcs1v15_check':
342  >ruby rsassa_pkcs1v15_check -f <file> [-c <file>] [-s <a>.<b>] [-n <name> | -l <file>]
343   -d          enable debugging (logging all received text, not only responses)
344   -c <file>   use <file> as configuration file
345   -f <file>   read testvectors from <file>
346   -s <a>.<b>  start with testvector <a>.<b>
347   -n <name>   log to a file which name is based on <name>
348
349 EOF
350
351 opts = Getopt::Std.getopts('dc:f:l:s:n:')
352
353 if !opts['f']
354   print help_text
355   exit 0
356 end
357
358 conf = Hash.new
359 conf = readconfigfile("/etc/testport.conf", conf)
360 conf = readconfigfile("~/.testport.conf", conf)
361 conf = readconfigfile("testport.conf", conf)
362 conf = readconfigfile(opts["c"], conf) if opts["c"]
363
364 #puts conf.inspect
365
366 puts("serial port interface version: " + SerialPort::VERSION);
367 $linewidth = 64
368 params = { "baud"       => conf["PORT"]["baud"].to_i,
369             "data_bits" => conf["PORT"]["databits"].to_i,
370             "stop_bits" => conf["PORT"]["stopbits"].to_i,
371             "parity"    => SerialPort::NONE }
372 params["paraty"] = SerialPort::ODD   if conf["PORT"]["paraty"].downcase == "odd"
373 params["paraty"] = SerialPort::EVEN  if conf["PORT"]["paraty"].downcase == "even"
374 params["paraty"] = SerialPort::MARK  if conf["PORT"]["paraty"].downcase == "mark"
375 params["paraty"] = SerialPort::SPACE if conf["PORT"]["paraty"].downcase == "space"
376
377 puts("\nPort: "+conf["PORT"]["port"]+"@"    +
378                 params["baud"].to_s      +
379                 " "                      +
380                 params["data_bits"].to_s +
381                 conf["PORT"]["paraty"][0,1].upcase +
382                 params["stop_bits"].to_s +
383                 "\n")
384
385 $sp = SerialPort.new(conf["PORT"]["port"], params)
386
387 $sp.read_timeout=1000; # 5 minutes
388 $sp.flow_control = SerialPort::SOFT
389
390 $debug = true if opts['d']
391
392 if opts['l'] && ! opts['n']
393   $logfile = File.open(opts['l'], 'w')
394 end
395
396 base_name = 'rsassa_pkcs1v15'
397
398 if opts['n']
399   logfilename = conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '.txt'
400   if File.exists?(logfilename)
401     i=1
402     begin
403       logfilename = sprintf('%s%04d%s', conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '_', i, '.txt')
404       i+=1
405     end while(File.exists?(logfilename))
406     while(i>2) do
407       n1 = sprintf('%s%04d%s', conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '_', i-2, '.txt')
408       n2 = sprintf('%s%04d%s', conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '_', i-1, '.txt')
409       File.rename(n1, n2)
410       printf("%s -> %s\n", n1, n2)
411       i-=1
412     end
413     n1 = sprintf('%s%s', conf['PORT']['testlogbase'], base_name + '_' + opts['n'] + '.txt')
414     n2 = sprintf('%s%04d%s', conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '_', 1, '.txt')
415     File.rename(n1, n2)
416     printf("%s -> %s\n", n1, n2)
417     logfilename = conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '.txt'
418   end
419   printf("logging to %s", logfilename)
420   $logfile = File.open(logfilename, 'w')
421 end
422
423 $logfile = STDOUT if ! $logfile
424 $logfile.sync = true
425 reset_system()
426
427 if opts['s'] && ( m = opts['s'].match(/([\d]+)\.([\d]+)/) )
428   sk = m[1].to_i
429   sv = m[2].to_i
430 else
431   sk = 1
432   sv = 1
433 end
434
435 f = File.open(opts['f'], "r")
436 exit if !f
437 ok,fail = process_file(f,sk,sv)
438 printf("\nOK: %d FAIL: %d :-%s\n",ok,fail, fail==0 ? ')':'(')
439
440