]> git.cryptolib.org Git - arm-crypto-lib.git/blob - host/rsaes_pkcs1v15_check.rb
fixing bugs reported by Christian Dernehl
[arm-crypto-lib.git] / host / rsaes_pkcs1v15_check.rb
1 #!/usr/bin/ruby
2 # rsaes_pkcs1v15_check.rb
3 =begin
4     This file is part of the AVR-Crypto-Lib.
5     Copyright (C) 2008  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 $progress_dots = false
30 $debug = 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       c = get_next_block(f)
192       tv = Hash.new
193       tv['msg'] = a['data']
194       tv['seed'] = b['data']
195       tv['enc'] = c['data'] 
196       skip_vec_flag = (skip_key_flag || (key_no == skip_key && vec_no < skip_vec))
197       if skip_vec_flag
198         printf('o')
199       else
200         v = check_tv(tv)
201         if(v == true)
202           printf('*')
203           $logfile.printf("[[Test %2d.%02d = OK]]\n", key_no, vec_no)
204           ok_counter += 1
205         else
206           printf('%c', v ? '*' : '!')
207           $logfile.printf("[[Test %2d.%02d = FAIL]]\n", key_no, vec_no)
208           fail_counter += 1
209         end
210       end
211       a = get_next_block(f)
212     end while a && a['tag'] == 'Message'
213   end while a && a['tag'] = 'Modulus'
214 #  printf("\nResult: %d OK / %d FAIL ==> %s \nFinished\n", ok_counter, fail_counter, fail_counter==0 ? ':-)' : ':-(')
215   return ok_counter,fail_counter
216 end
217
218 def convert_key(k_seq)
219   l = ['n', 'e', 'd', 'p', 'q', 'dP', 'dQ', 'qInv']
220   r = Hash.new
221   return nil if k_seq[0]['data'] != k_seq[2]['data']
222   return nil if k_seq[1]['data'] != k_seq[3]['data']
223   8.times do |i|
224     r[l[i]] = k_seq[2 + i]['data'] 
225   end
226   return r
227 end
228
229 def wait_for_dot
230   begin
231     s = $sp.gets()
232   end while !s || !s.include?('.')
233 end
234
235 def load_bigint(d)
236   $sp.printf("%d\r", d.length)
237   while l = read_line_from_device()
238     break if /data:/.match(l)
239   end
240   printf "ERROR: got no answer from system!" if !l
241   i = 0
242   d.each do |e|
243     $sp.printf("%02x", e)
244     i += 1
245     if i % 60 == 0
246 # we should now wait for incomming dot
247       wait_for_dot()
248       print('.') if $progress_dots
249     end
250   end
251 end
252
253 def hexdump(a)
254   i = 0
255   a.each do |e|
256     printf("\n\t") if i % 16 == 0
257     printf('%02x ', e)
258     i += 1
259   end
260   puts('') if i % 16 != 1
261 end
262
263 def str_hexdump(a)
264   i = 0
265   s = ''
266   a.each do |e|
267     s += "\n\t" if i % 16 == 0
268     s += sprintf('%02x ', e)
269     i += 1
270   end
271   s += "\n" if i % 16 != 1
272   return s
273 end
274
275 def load_key(k)
276   $sp.print("load-key\r")
277   sleep 0.1
278   v = ['n', 'e', 'p', 'q', 'dP', 'dQ', 'qInv']  
279   v.each do |e|
280     load_bigint(k[e])
281     $logfile.printf("DBG: loaded %s\n", e) if $debug
282   end 
283   while l = read_line_from_device()
284     break if />/.match(l)
285   end
286 end
287
288 def strip_leading_zeros(a)
289   loop do
290     return [] if a.length == 0
291     return a if a[0] != 0
292     a.delete_at(0)
293   end
294 end
295
296 def check_tv(tv)
297   sleep 0.1
298   $sp.print("seed-test\r")
299   sleep 0.1
300   load_bigint(tv['msg'])
301   $logfile.printf("DBG: loaded %s\n", 'msg') if $debug
302   sleep 0.1
303   tv['seed'].each { |e| $sp.printf(" %02x", e) } 
304   while l = read_line_from_device() 
305     break if /ciphertext:/.match(l)
306   end
307   test_enc = ''
308   loop do 
309     l = read_line_from_device()
310     t = l.split
311     v = false
312     t.each { |e| v = true if e.length != 2 }
313     x = t.collect { |e| e.to_i(16) }
314     break if v
315     test_enc += l if l
316   end
317   test_enc_a = Array.new
318   test_enc = test_enc.split(/[\W\r\n]+/)
319   test_enc.each do |e|
320     v = e.sub(/[^0-9A-Fa-f]/, '') 
321     test_enc_a << v if v.length == 2
322   end
323   test_enc_a.collect!{ |e| e.to_i(16) }
324   strip_leading_zeros(test_enc_a)
325   strip_leading_zeros(tv['enc'])
326   enc_ok = (test_enc_a == tv['enc'])
327   if !enc_ok
328     $logfile.printf("DBG: ref = %s test = %s\n", str_hexdump(tv['enc']) , str_hexdump(test_enc_a))
329   end
330   m = nil
331   loop do 
332     l = read_line_from_device() 
333     m = /(>>OK<<|ERROR)/.match(l)
334     break if m
335   end
336   return true if enc_ok && (m[1] == '>>OK<<') 
337   return false
338 end
339
340 ########################################
341 # MAIN
342 ########################################
343 help_text = <<EOF
344 Usage of 'rsaes_pkcs1v15_check':
345  >ruby rsaes_pkcs1v15_check -f <file> [-c <file>] [-s <a>.<b>] [-n <name> | -l <file>]
346   -d          enable debugging (logging all received text, not only responses)
347   -c <file>   use <file> as configuration file
348   -f <file>   read testvectors from <file>
349   -s <a>.<b>  start with testvector <a>.<b>
350   -n <name>   log to a file which name is based on <name>
351
352 EOF
353
354 opts = Getopt::Std.getopts('dc:f:l:s:n:')
355
356 if !opts['f']
357   print help_text
358   exit 0
359 end
360
361 conf = Hash.new
362 conf = readconfigfile("/etc/testport.conf", conf)
363 conf = readconfigfile("~/.testport.conf", conf)
364 conf = readconfigfile("testport.conf", conf)
365 conf = readconfigfile(opts["c"], conf) if opts["c"]
366
367 #puts conf.inspect
368
369 puts("serial port interface version: " + SerialPort::VERSION);
370 $linewidth = 64
371 params = { "baud"       => conf["PORT"]["baud"].to_i,
372             "data_bits" => conf["PORT"]["databits"].to_i,
373             "stop_bits" => conf["PORT"]["stopbits"].to_i,
374             "parity"    => SerialPort::NONE }
375 params["paraty"] = SerialPort::ODD   if conf["PORT"]["paraty"].downcase == "odd"
376 params["paraty"] = SerialPort::EVEN  if conf["PORT"]["paraty"].downcase == "even"
377 params["paraty"] = SerialPort::MARK  if conf["PORT"]["paraty"].downcase == "mark"
378 params["paraty"] = SerialPort::SPACE if conf["PORT"]["paraty"].downcase == "space"
379
380 puts("\nPort: "+conf["PORT"]["port"]+"@"    +
381                 params["baud"].to_s      +
382                 " "                      +
383                 params["data_bits"].to_s +
384                 conf["PORT"]["paraty"][0,1].upcase +
385                 params["stop_bits"].to_s +
386                 "\n")
387
388 $sp = SerialPort.new(conf["PORT"]["port"], params)
389
390 $sp.read_timeout=1000; # 5 minutes
391 $sp.flow_control = SerialPort::SOFT
392
393 $debug = true if opts['d']
394
395 if opts['l'] && ! opts['n']
396   $logfile = File.open(opts['l'], 'w')
397 end
398
399 base_name = 'rsaes_pkcs1v15'
400
401 if opts['n']
402   logfilename = conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '.txt'
403   if File.exists?(logfilename)
404     i=1
405     begin
406       logfilename = sprintf('%s%04d%s', conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '_',i,'.txt')
407       i+=1
408     end while(File.exists?(logfilename))
409     while(i>2) do
410       n1 = sprintf('%s%04d%s', conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '_', i-2, '.txt')
411       n2 = sprintf('%s%04d%s', conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '_', i-1, '.txt')
412       File.rename(n1, n2)
413       printf("%s -> %s\n", n1, n2)
414       i-=1
415     end
416     n1 = sprintf('%s%s', conf['PORT']['testlogbase'], base_name + '_' + opts['n'] + '.txt')
417     n2 = sprintf('%s%04d%s', conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '_', 1, '.txt')
418     File.rename(n1, n2)
419     printf("%s -> %s\n", n1, n2)
420     logfilename = conf['PORT']['testlogbase'] + base_name + '_' + opts['n'] + '.txt'
421   end
422   printf("logging to %s", logfilename)
423   $logfile = File.open(logfilename, 'w')
424 end
425
426 $logfile = STDOUT if ! $logfile
427 $logfile.sync = true
428 reset_system()
429
430 if opts['s'] && ( m = opts['s'].match(/([\d]+)\.([\d]+)/) )
431   sk = m[1].to_i
432   sv = m[2].to_i
433 else
434   sk = 1
435   sv = 1
436 end
437
438 f = File.open(opts['f'], "r")
439 exit if !f
440 ok,fail = process_file(f,sk,sv)
441 printf("\nOK: %d FAIL: %d :-%s\n",ok,fail, fail==0 ? ')':'(')
442
443