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