2 # rsa_pkcs1v15_check.rb
4 This file is part of the AVR-Crypto-Lib.
5 Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de)
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.
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.
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/>.
26 $buffer_size = 0 # set automatically in init_system
27 $conffile_check = Hash.new
28 $conffile_check.default = 0
32 ################################################################################
34 ################################################################################
36 def read_line_from_device()
37 repeat_counter = 10000
43 end while !l && repeat_counter > 0
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")
53 def readconfigfile(fname, conf)
54 return conf if $conffile_check[fname]==1
55 $conffile_check[fname]=1
57 if not File.exists?(fname)
60 file = File.open(fname, "r")
63 next if /[\s]*#/.match(line)
64 if m=/\[[\s]*([^\s]*)[\s]*\]/.match(line)
69 next if ! /=/.match(line)
70 m=/[\s]*([^\s]*)[\s]*=[\s]*([^\s]*)/.match(line)
72 Dir.glob(m[2]){ |fn| conf = readconfigfile(fn, conf) }
74 conf[section][m[1]] = m[2]
81 ################################################################################
83 ################################################################################
90 $sp.print("echo off\r")
100 # x = l.split.collect { |e| e.to_i(16) }
102 t.each { |e| v = true if e.length != 2 }
104 x = t.collect { |e| e.to_i(16) } if ! v
106 end while x.length == 16 && ! v
127 def get_next_block(f)
132 end while l && ! m= l.match(/^#[\s](.*):[\s]*$/)
135 ret['line'] = f.lineno
145 'Public exponent', # 3
149 'Prime exponent 1', # 7
150 'Prime exponent 2', # 8
154 def key_consitency_check(k)
158 def process_file(f, skip_key=1, skip_vec=1)
159 a = get_next_block(f)
164 if !a || ! a['tag'] == 'Modulus'
165 printf("ERROR: a = %s %d\n", a.inspect, __LINE__)
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__)
177 key = convert_key(k_seq)
178 printf("ERROR: %d\n", __LINE__) if ! key
181 printf("\n run %3d: ", key_no)
182 skip_key_flag = (key_no < skip_key)
183 load_key(key) if ! skip_key_flag
185 a = get_next_block(f)
186 printf("ERROR: %d\n", __LINE__) if ! a
189 b = get_next_block(f)
190 c = get_next_block(f)
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))
202 $logfile.printf("[[Test %2d.%02d = OK]]\n", key_no, vec_no)
205 printf('%c', v ? '*' : '!')
206 $logfile.printf("[[Test %2d.%02d = FAIL]]\n", key_no, vec_no)
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
217 def convert_key(k_seq)
218 l = ['n', 'e', 'd', 'p', 'q', 'dP', 'dQ', 'qInv']
220 return nil if k_seq[0]['data'] != k_seq[2]['data']
221 return nil if k_seq[1]['data'] != k_seq[3]['data']
223 r[l[i]] = k_seq[2 + i]['data']
231 end while !s || !s.include?('.')
235 $sp.printf("%d\r", d.length)
236 while l = read_line_from_device()
237 break if /data:/.match(l)
239 printf "ERROR: got no answer from system!" if !l
242 $sp.printf("%02x", e)
245 # we should now wait for incomming dot
255 printf("\n\t") if i % 16 == 0
259 puts('') if i % 16 != 1
266 s += "\n\t" if i % 16 == 0
267 s += sprintf('%02x ', e)
270 s += "\n" if i % 16 != 1
275 $sp.print("load-key\r")
277 v = ['n', 'e', 'p', 'q', 'dP', 'dQ', 'qInv']
280 $logfile.printf("DBG: loaded %s\n", e) if $debug
282 while l = read_line_from_device()
283 break if />/.match(l)
287 def strip_leading_zeros(a)
289 return [] if a.length == 0
290 return a if a[0] != 0
297 $sp.print("seed-test\r")
299 load_bigint(tv['msg'])
300 $logfile.printf("DBG: loaded %s\n", 'msg') if $debug
302 tv['seed'].each { |e| $sp.printf(" %02x", e) }
303 while l = read_line_from_device()
304 break if /ciphertext:/.match(l)
308 l = read_line_from_device()
311 t.each { |e| v = true if e.length != 2 }
312 x = t.collect { |e| e.to_i(16) }
316 test_enc_a = Array.new
317 test_enc = test_enc.split(/[\W\r\n]+/)
319 v = e.sub(/[^0-9A-Fa-f]/, '')
320 test_enc_a << v if v.length == 2
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'])
327 $logfile.printf("DBG: ref = %s test = %s\n", str_hexdump(tv['enc']) , str_hexdump(test_enc_a))
331 l = read_line_from_device()
332 m = /(>>OK<<|ERROR)/.match(l)
335 return true if enc_ok && (m[1] == '>>OK<<')
339 ########################################
341 ########################################
344 opts = Getopt::Std.getopts('dc:f:il:s:n:')
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"]
354 puts("serial port interface version: " + SerialPort::VERSION);
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"
365 puts("\nPort: "+conf["PORT"]["port"]+"@" +
366 params["baud"].to_s +
368 params["data_bits"].to_s +
369 conf["PORT"]["paraty"][0,1].upcase +
370 params["stop_bits"].to_s +
373 $sp = SerialPort.new(conf["PORT"]["port"], params)
375 $sp.read_timeout=1000; # 5 minutes
376 $sp.flow_control = SerialPort::SOFT
378 $debug = true if opts['d']
380 if opts['l'] && ! opts['n']
381 $logfile = File.open(opts['l'], 'w')
385 logfilename = conf['PORT']['testlogbase']+'rsa_pkcs1v15_' + opts['n'] + '.txt'
386 if File.exists?(logfilename)
389 logfilename = sprintf('%s%04d%s', conf['PORT']['testlogbase']+'rsa_pkcs1v15_'+opts['n']+'_',i,'.txt')
391 end while(File.exists?(logfilename))
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')
396 printf("%s -> %s\n", n1, n2)
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')
402 printf("%s -> %s\n", n1, n2)
403 logfilename = conf['PORT']['testlogbase']+'rsa_pkcs1v15_'+opts['n']+'.txt'
405 printf("logging to %s", logfilename)
406 $logfile = File.open(logfilename, 'w')
409 $logfile = STDOUT if ! $logfile
413 if opts['s'] && ( m = opts['s'].match(/([\d]+)\.([\d]+)/) )
421 f = File.open(opts['f'], "r")
423 ok,fail = process_file(f,sk,sv)
424 printf("\nOK: %d FAIL: %d :-%s\n",ok,fail, fail==0 ? ')':'(')