]> git.cryptolib.org Git - avr-crypto-lib.git/blob - host/rsa_pkcs1v15_check.rb
present looks better now (using unverified testvectors)
[avr-crypto-lib.git] / host / rsa_pkcs1v15_check.rb
1 #!/usr/bin/ruby
2 # rsa_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 $debug = false
30 $logfile = nil
31
32 ################################################################################
33 # readconfigfile                                                               #
34 ################################################################################
35
36 def read_line_from_device()
37   repeat_counter = 10000
38   l = nil
39   s = ''
40   begin
41     l = $sp.gets()
42     repeat_counter -= 1
43   end while !l && repeat_counter > 0
44   t = Time.new
45   $logfile.printf("DBG: (%02d:%02d:%02d)<< %s\n", t.hour, t.min, t.sec, l.inspect) if $debug
46   if l && l.include?("AVR-Crypto-Lib")
47     $logfile.printf("DBG: system crashed !!!\n")
48     exit(false)
49   end
50   return l
51 end
52
53 def readconfigfile(fname, conf)
54   return conf if $conffile_check[fname]==1
55   $conffile_check[fname]=1
56   section = "default"
57   if not File.exists?(fname)
58     return conf
59   end
60   file = File.open(fname, "r")
61   until file.eof
62     line = file.gets()
63           next if /[\s]*#/.match(line)
64         if m=/\[[\s]*([^\s]*)[\s]*\]/.match(line)
65             section=m[1]
66             conf[m[1]] = Hash.new
67             next
68           end
69           next if ! /=/.match(line)
70           m=/[\s]*([^\s]*)[\s]*=[\s]*([^\s]*)/.match(line)
71           if m[1]=="include"
72             Dir.glob(m[2]){ |fn| conf = readconfigfile(fn, conf) }
73           else
74           conf[section][m[1]] = m[2]
75           end
76   end
77   file.close()
78   return conf
79 end
80
81 ################################################################################
82 # reset_system                                                                 #
83 ################################################################################
84
85 def reset_system
86   $sp.print("\r")
87   sleep 0.1
88   $sp.print("\r")
89   sleep 0.1
90   $sp.print("echo off\r")
91   sleep 0.1
92 end
93
94
95 def read_block(f)
96   d = Array.new
97   begin
98     v = false
99     l = f.gets
100  #   x = l.split.collect { |e| e.to_i(16) }
101     t = l.split
102     t.each { |e| v = true if e.length != 2 }
103     x = []
104     x = t.collect { |e| e.to_i(16) } if ! v
105     d += x
106   end while x.length == 16 && ! v
107   return d
108 end
109
110 =begin
111 # Modulus: 
112 # Exponent: 
113 # Modulus: 
114 # Public exponent: 
115 # Exponent: 
116 # Prime 1: 
117 # Prime 2: 
118 # Prime exponent 1: 
119 # Prime exponent 2: 
120 # Coefficient: 
121 # Message:
122 # Seed:
123 # Encryption:
124
125 =end
126
127 def get_next_block(f)
128   ret = Hash.new
129   data = Array.new
130   begin
131     l = f.gets
132   end while l && ! m= l.match(/^#[\s](.*):[\s]*$/)
133   return nil if ! l
134   ret['tag'] = m[1]
135   ret['line'] = f.lineno
136   data = read_block(f)
137   ret['data'] = data
138   return ret
139 end
140
141 $key_sequence = [
142   'Modulus',             # 0
143   'Exponent',            # 1
144   'Modulus',             # 2
145   'Public exponent',     # 3
146   'Exponent',            # 4
147   'Prime 1',             # 5
148   'Prime 2',             # 6
149   'Prime exponent 1',    # 7
150   'Prime exponent 2',    # 8
151   'Coefficient',         # 9
152 ]
153
154 def key_consitency_check(k)
155   return true
156 end
157
158 def process_file(f, skip_key=1, skip_vec=1)
159   a = get_next_block(f)
160   key_no = 0
161   ok_counter = 0
162   fail_counter = 0
163   begin
164     if !a || ! a['tag'] == 'Modulus'
165       printf("ERROR: a = %s %d\n", a.inspect, __LINE__)
166       return
167     end
168     k_seq = Array.new
169     k_seq[0] = a
170     (1..($key_sequence.length-1)).each do |i|
171       a = get_next_block(f)
172       if ! a || a['tag'] != $key_sequence[i]
173         printf("ERROR: (expecting: %s) a = %s %d\n", $key_sequence[i], a.inspect, __LINE__)
174       end
175       k_seq[i] = a
176     end
177     key = convert_key(k_seq)
178     printf("ERROR: %d\n", __LINE__) if ! key
179     key_no += 1
180     vec_no = 0
181     printf("\n run %3d: ", key_no)
182     skip_key_flag = (key_no < skip_key)
183     load_key(key) if ! skip_key_flag
184     test_seq = Array.new
185     a = get_next_block(f)
186     printf("ERROR: %d\n", __LINE__) if ! a 
187     begin
188       vec_no += 1
189       b = get_next_block(f)
190       c = get_next_block(f)
191       tv = Hash.new
192       tv['msg'] = a['data']
193       tv['seed'] = b['data']
194       tv['enc'] = c['data'] 
195       skip_vec_flag = (skip_key_flag || (key_no == skip_key && vec_no < skip_vec))
196       if skip_vec_flag
197         printf('o')
198       else
199         v = check_tv(tv)
200         if(v == true)
201           printf('*')
202           $logfile.printf("[[Test %2d.%02d = OK]]\n", key_no, vec_no)
203           ok_counter += 1
204         else
205           printf('%c', v ? '*' : '!')
206           $logfile.printf("[[Test %2d.%02d = FAIL]]\n", key_no, vec_no)
207           fail_counter += 1
208         end
209       end
210       a = get_next_block(f)
211     end while a && a['tag'] == 'Message'
212   end while a && a['tag'] = 'Modulus'
213 #  printf("\nResult: %d OK / %d FAIL ==> %s \nFinished\n", ok_counter, fail_counter, fail_counter==0 ? ':-)' : ':-(')
214   return ok_counter,fail_counter
215 end
216
217 def convert_key(k_seq)
218   l = ['n', 'e', 'd', 'p', 'q', 'dP', 'dQ', 'qInv']
219   r = Hash.new
220   return nil if k_seq[0]['data'] != k_seq[2]['data']
221   return nil if k_seq[1]['data'] != k_seq[3]['data']
222   8.times do |i|
223     r[l[i]] = k_seq[2 + i]['data'] 
224   end
225   return r
226 end
227
228 def wait_for_dot
229   begin
230     s = $sp.gets()
231   end while !s || !s.include?('.')
232 end
233
234 def load_bigint(d)
235   $sp.printf("%d\r", d.length)
236   while l = read_line_from_device()
237     break if /data:/.match(l)
238   end
239   printf "ERROR: got no answer from system!" if !l
240   i = 0
241   d.each do |e|
242     $sp.printf("%02x", e)
243     i += 1
244     if i % 60 == 0
245 # we should now wait for incomming dot
246       wait_for_dot()
247       print('.')
248     end
249   end
250 end
251
252 def hexdump(a)
253   i = 0
254   a.each do |e|
255     printf("\n\t") if i % 16 == 0
256     printf('%02x ', e)
257     i += 1
258   end
259   puts('') if i % 16 != 1
260 end
261
262 def str_hexdump(a)
263   i = 0
264   s = ''
265   a.each do |e|
266     s += "\n\t" if i % 16 == 0
267     s += sprintf('%02x ', e)
268     i += 1
269   end
270   s += "\n" if i % 16 != 1
271   return s
272 end
273
274 def load_key(k)
275   $sp.print("load-key\r")
276   sleep 0.1
277   v = ['n', 'e', 'p', 'q', 'dP', 'dQ', 'qInv']  
278   v.each do |e|
279     load_bigint(k[e])
280     $logfile.printf("DBG: loaded %s\n", e) if $debug
281   end 
282   while l = read_line_from_device()
283     break if />/.match(l)
284   end
285 end
286
287 def strip_leading_zeros(a)
288   loop do
289     return [] if a.length == 0
290     return a if a[0] != 0
291     a.delete_at(0)
292   end
293 end
294
295 def check_tv(tv)
296   sleep 0.1
297   $sp.print("seed-test\r")
298   sleep 0.1
299   load_bigint(tv['msg'])
300   $logfile.printf("DBG: loaded %s\n", 'msg') if $debug
301   sleep 0.1
302   tv['seed'].each { |e| $sp.printf(" %02x", e) } 
303   while l = read_line_from_device() 
304     break if /ciphertext:/.match(l)
305   end
306   test_enc = ''
307   loop do 
308     l = read_line_from_device()
309     t = l.split
310     v = false
311     t.each { |e| v = true if e.length != 2 }
312     x = t.collect { |e| e.to_i(16) }
313     break if v
314     test_enc += l if l
315   end
316   test_enc_a = Array.new
317   test_enc = test_enc.split(/[\W\r\n]+/)
318   test_enc.each do |e|
319     v = e.sub(/[^0-9A-Fa-f]/, '') 
320     test_enc_a << v if v.length == 2
321   end
322   test_enc_a.collect!{ |e| e.to_i(16) }
323   strip_leading_zeros(test_enc_a)
324   strip_leading_zeros(tv['enc'])
325   enc_ok = (test_enc_a == tv['enc'])
326   if !enc_ok
327     $logfile.printf("DBG: ref = %s test = %s\n", str_hexdump(tv['enc']) , str_hexdump(test_enc_a))
328   end
329   m = nil
330   loop do 
331     l = read_line_from_device() 
332     m = /(>>OK<<|ERROR)/.match(l)
333     break if m
334   end
335   return true if enc_ok && (m[1] == '>>OK<<') 
336   return false
337 end
338
339 ########################################
340 # MAIN
341 ########################################
342
343
344 opts = Getopt::Std.getopts('dc:f:il:s:n:')
345
346 conf = Hash.new
347 conf = readconfigfile("/etc/testport.conf", conf)
348 conf = readconfigfile("~/.testport.conf", conf)
349 conf = readconfigfile("testport.conf", conf)
350 conf = readconfigfile(opts["c"], conf) if opts["c"]
351
352 #puts conf.inspect
353
354 puts("serial port interface version: " + SerialPort::VERSION);
355 $linewidth = 64
356 params = { "baud"       => conf["PORT"]["baud"].to_i,
357             "data_bits" => conf["PORT"]["databits"].to_i,
358             "stop_bits" => conf["PORT"]["stopbits"].to_i,
359             "parity"    => SerialPort::NONE }
360 params["paraty"] = SerialPort::ODD   if conf["PORT"]["paraty"].downcase == "odd"
361 params["paraty"] = SerialPort::EVEN  if conf["PORT"]["paraty"].downcase == "even"
362 params["paraty"] = SerialPort::MARK  if conf["PORT"]["paraty"].downcase == "mark"
363 params["paraty"] = SerialPort::SPACE if conf["PORT"]["paraty"].downcase == "space"
364
365 puts("\nPort: "+conf["PORT"]["port"]+"@"    +
366                 params["baud"].to_s      +
367                 " "                      +
368                 params["data_bits"].to_s +
369                 conf["PORT"]["paraty"][0,1].upcase +
370                 params["stop_bits"].to_s +
371                 "\n")
372
373 $sp = SerialPort.new(conf["PORT"]["port"], params)
374
375 $sp.read_timeout=1000; # 5 minutes
376 $sp.flow_control = SerialPort::SOFT
377
378 $debug = true if opts['d']
379
380 if opts['l'] && ! opts['n']
381   $logfile = File.open(opts['l'], 'w')
382 end
383
384 if opts['n']
385   logfilename = conf['PORT']['testlogbase']+'rsa_pkcs1v15_' + opts['n'] + '.txt'
386   if File.exists?(logfilename)
387     i=1
388     begin
389       logfilename = sprintf('%s%04d%s', conf['PORT']['testlogbase']+'rsa_pkcs1v15_'+opts['n']+'_',i,'.txt')
390       i+=1
391     end while(File.exists?(logfilename))
392     while(i>2) do
393       n1 = sprintf('%s%04d%s', conf['PORT']['testlogbase']+'rsa_pkcs1v15_'+opts['n']+'_',i-2,'.txt')
394       n2 = sprintf('%s%04d%s', conf['PORT']['testlogbase']+'rsa_pkcs1v15_'+opts['n']+'_',i-1,'.txt')
395       File.rename(n1, n2)
396       printf("%s -> %s\n", n1, n2)
397       i-=1
398     end
399     n1 = sprintf('%s%s', conf['PORT']['testlogbase'],'rsa_pkcs1v15_'+opts['n']+'.txt')
400     n2 = sprintf('%s%04d%s', conf['PORT']['testlogbase']+'rsa_pkcs1v15_'+opts['n']+'_',1,'.txt')
401     File.rename(n1, n2)
402     printf("%s -> %s\n", n1, n2)
403     logfilename = conf['PORT']['testlogbase']+'rsa_pkcs1v15_'+opts['n']+'.txt'
404   end
405   printf("logging to %s", logfilename)
406   $logfile = File.open(logfilename, 'w')
407 end
408
409 $logfile = STDOUT if ! $logfile
410 $logfile.sync = true
411 reset_system()
412
413 if opts['s'] && ( m = opts['s'].match(/([\d]+)\.([\d]+)/) )
414   sk = m[1].to_i
415   sv = m[2].to_i
416 else
417   sk = 1
418   sv = 1
419 end
420
421 f = File.open(opts['f'], "r")
422 exit if !f
423 ok,fail = process_file(f,sk,sv)
424 printf("\nOK: %d FAIL: %d :-%s\n",ok,fail, fail==0 ? ')':'(')
425
426