]> git.cryptolib.org Git - avr-crypto-lib.git/blob - host/cmacvs_test.rb
fixing E-Mail-Address & Copyright
[avr-crypto-lib.git] / host / cmacvs_test.rb
1 #!/usr/bin/ruby
2 # cmacvs_test.rb
3 =begin
4     This file is part of the AVR-Crypto-Lib.
5     Copyright (C) 2006-2015 Daniel Otte (bg@nerilex.org)
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 $debug = true
22 $debug = false
23 require 'rubygems'
24 require 'serialport'
25 require 'getopt/std'
26
27 $buffer_size = 0
28 $conffile_check = Hash.new
29 $conffile_check.default = 0
30
31 ################################################################################
32 # readconfigfile                                                               #
33 ################################################################################
34
35 def readconfigfile(fname, conf)
36   return conf if $conffile_check[fname]==1
37   $conffile_check[fname]=1
38   section = "default"
39   if not File.exists?(fname)
40     return conf
41   end
42   file = File.open(fname, "r")
43   until file.eof
44     line = file.gets()
45         next if /[\s]*#/.match(line)
46         if m=/\[[\s]*([^\s]*)[\s]*\]/.match(line)
47           section=m[1]
48           conf[m[1]] = Hash.new
49           next
50         end
51         next if not /=/.match(line)
52         m=/[\s]*([^\s]*)[\s]*=[\s]*([^\s]*)/.match(line)
53         if m[1]=="include"
54           Dir.glob(m[2]){ |fn| conf = readconfigfile(fn, conf) }
55         else
56           conf[section][m[1]] = m[2]
57         end
58   end
59   file.close()
60   return conf
61 end
62
63 ################################################################################
64 # reset_system                                                                 #
65 ################################################################################
66
67 def reset_system
68   $sp.print("exit\r")
69   sleep 0.1
70   $sp.print("exit\r")
71   sleep 0.1
72 end
73
74 ################################################################################
75 # scan_system                                                                  #
76 ################################################################################
77
78 def scan_system
79   algos = Hash.new
80   $sp.print("cmacvs_list\r")
81   while true
82     line=$sp.gets()
83     return algos if /^>$/.match(line)
84     if m = /[\*\ ]([a-z]):[\s]*([a-zA-Z0-9+_-]+)/.match(line)
85       algos[m[2]]=m[1]
86     end
87   end
88 end
89
90 ################################################################################
91 # init_system                                                                  #
92 ################################################################################
93
94 def init_system(algo_select, algo_id)
95   $sp.print("echo off \r")
96   print("DBG i: " + "echo off \r"+"\n") if $debug
97  sleep 1
98   $sp.print("cmacvs_set #{algo_select}\r")
99   print("DBG i: " + "cmacvs_set #{$algo_select} \r"+"\n") if $debug
100   sleep 1
101   $sp.print("cmacvs_test#{algo_id} \r")
102   print("DBG i: " + "cmacvs_test#{algo_id} \r"+"\n") if $debug
103   begin
104     line=$sp.gets()
105   end while not m=/buffer_size[\s]*=[\s]*0x([0-9A-Fa-f]*)/.match(line)
106   $buffer_size = m[1].to_i(16)
107 end
108
109 ################################################################################
110 # get_md                                                                       #
111 ################################################################################
112
113 def get_mac
114   begin
115     line = $sp.gets()
116         line = "" if line==nil
117         puts("DBG got: "+line) if $debug
118   end while not /[\s]*Mac[\s]*=.*/.match(line)
119   return line
120 end
121
122 ################################################################################
123 # get_result                                                                   #
124 ################################################################################
125
126 def get_result
127   begin
128     line = $sp.gets()
129     line = "" if line==nil
130     puts("DBG got: "+line) if $debug
131   end while not /[\s]*Result[\s]*=.*/.match(line)
132   puts "DBG i: got result: "+line if $debug
133   return line
134 end
135
136 ################################################################################
137 # send_md                                                                      #
138 ################################################################################
139
140 def send_test(klen, mlen, tlen, key, msg, mac=nil)
141   $sp.printf("Klen = %s\n\r", klen)
142   $sp.printf("Mlen = %s\n\r", mlen)
143   $sp.printf("Tlen = %s\n\r", tlen)
144   $sp.printf("Key = %s\n\r",  key)
145   $sp.print("Msg = ")
146   for i in 0..msg.length-1
147     $sp.print(msg[i].chr)
148 #   print("DBG s: "+ md_string[i].chr) if $debug
149 #   sleep(0.001)
150     if((i%($buffer_size*2)==0)&&(i!=0))
151       begin
152       line=$sp.gets()
153       end while not /\./.match(line)
154     end
155   end
156   $sp.printf("Mac = %s\n\r",  mac) if mac
157 end
158
159 ################################################################################
160 # get_next_kv_pair                                                             #
161 ################################################################################
162
163 def get_next_kv_pair(file)
164   loop do
165     return nil if file.eof
166     lb = file.gets()
167     m=lb.match(/[\s]*([\w\d_-]*)[\s]*=[\s]*([\w\d_-]*)/)
168     puts "DBG i: found #{m[1]} with value #{m[2]}" if m && $debug
169     return [m[1],m[2]] if m
170   end
171 end
172
173 ################################################################################
174 # run_test_gen                                                                 #
175 ################################################################################
176
177 def run_test_gen(filename, skip=0)
178   nerrors = 0
179   line=1
180   if not File.exist?(filename)
181         puts("ERROR file "+filename+" does not exist!")
182         return nerrors
183   end
184   pos = 0
185   file = File.new(filename, "r");
186   until file.eof
187     params = Hash.new
188     begin
189       m = get_next_kv_pair(file)
190       return nerrors if m==nil
191       params[m[0]] = m[1]
192     end until m[0]=='Mac'
193     if(skip>0)
194           skip -= 1
195           redo
196         end
197     puts("DBG sending: ") if $debug
198           send_test(params['Klen'], params['Mlen'], params['Tlen'], params['Key'], params['Msg'])
199           avr_md = get_mac()
200     a = params['Mac'];
201           b = (/[\s]*Mac[\s]*=[\s]*([0-9a-fA-F]*).*/.match(avr_md))[1];
202         a.upcase!
203         b.upcase!
204           printf("\n%4d (%4d) [%5d]: ", line, (line-1)*$linewidth, params['Count']) if (pos%$linewidth==0 and $linewidth!=0)
205           line += 1               if (pos%$linewidth==0 and $linewidth!=0)
206           #sleep(1)
207           #putc((a==b)?'*':'!')
208         if(a==b)
209             putc('*')
210         else
211             putc('!')
212          #  printf("<%d>",len)
213             printf("\nError @%05d: %s [should]\n           != %s [is]- ",  params['Count'].to_i , a, b)
214             nerrors += 1
215           end
216           pos += 1
217   end
218   file.close()
219   return nerrors
220 end
221
222 ################################################################################
223 # run_test_ver                                                                 #
224 ################################################################################
225
226 def run_test_ver(filename, skip=0)
227   nerrors = 0
228   line=1
229   if not File.exist?(filename)
230     puts("ERROR file "+filename+" does not exist!")
231     return nerrors
232   end
233   pos = 0
234   file = File.new(filename, "r");
235   until file.eof
236     params = Hash.new
237     begin
238       m = get_next_kv_pair(file)
239       return nerrors if m==nil
240       params[m[0]] = m[1]
241     end until m[0]=='Result'
242     if(skip>0)
243       skip -= 1
244       redo
245     end
246     puts("DBG sending: ") if $debug
247     send_test(params['Klen'], params['Mlen'], params['Tlen'], params['Key'], params['Msg'], params['Mac'])
248     avr_res = get_result()
249     a = params['Result'].match(/[\s]*([PF])/)[1];
250     b = /[\s]*Result[\s]*=[\s]*([PF])/.match(avr_res)[1];
251     a.upcase!
252     b.upcase!
253     printf("\n%4d (%4d) [%5d]: ", line, (line-1)*$linewidth, params['Count']) if (pos%$linewidth==0 and $linewidth!=0)
254     line += 1               if (pos%$linewidth==0 and $linewidth!=0)
255     #sleep(1)
256     #putc((a==b)?'*':'!')
257     if(a==b)
258       putc('*')
259     else
260       putc('!')
261    #  printf("<%d>",len)
262       printf("\nError @%05d: %s [should]\n           != %s [is]- ",  params['Count'].to_i , a, b)
263       nerrors += 1
264     end
265     pos += 1
266   end
267   file.close()
268   return nerrors
269 end
270
271 ################################################################################
272 # MAIN                                                                         #
273 ################################################################################
274
275 opts = Getopt::Std.getopts("s:f:i:j:hdca")
276
277 conf = Hash.new
278 conf = readconfigfile("/etc/testport.conf", conf)
279 conf = readconfigfile("~/.testport.conf", conf)
280 conf = readconfigfile("testport.conf", conf)
281 conf = readconfigfile(opts["f"], conf) if opts["f"]
282
283 #puts conf.inspect
284
285 puts("serial port interface version: " + SerialPort::VERSION);
286 $linewidth = 64
287 params = { "baud"       => conf["PORT"]["baud"].to_i,
288             "data_bits" => conf["PORT"]["databits"].to_i,
289             "stop_bits" => conf["PORT"]["stopbits"].to_i,
290             "parity"    => SerialPort::NONE }
291 params["paraty"] = SerialPort::ODD   if conf["PORT"]["paraty"].downcase == "odd"
292 params["paraty"] = SerialPort::EVEN  if conf["PORT"]["paraty"].downcase == "even"
293 params["paraty"] = SerialPort::MARK  if conf["PORT"]["paraty"].downcase == "mark"
294 params["paraty"] = SerialPort::SPACE if conf["PORT"]["paraty"].downcase == "space"
295
296 puts("\nPort: "+conf["PORT"]["port"]+"@"    +
297                 params["baud"].to_s      +
298                 " "                      +
299                 params["data_bits"].to_s +
300                 conf["PORT"]["paraty"][0,1].upcase +
301                 params["stop_bits"].to_s +
302                 "\n")
303
304 $sp = SerialPort.new(conf["PORT"]["port"], params)
305
306 $sp.read_timeout=1000; # 5 minutes
307 $sp.flow_control = SerialPort::SOFT
308
309 reset_system()
310 algos=scan_system()
311 #puts algos.inspect
312
313 if opts["d"]
314   $debug = true
315 end
316
317 if opts["s"]
318   algos_rev = algos.invert
319   algo_tasks = Array.new
320   opts["s"].each_byte{ |x|
321     if algos_rev[x.chr]
322       algo_tasks << [algos_rev[x.chr],x.chr]
323     end
324   }
325 else
326   algo_tasks=algos.sort
327 end
328
329 algo_tasks.each do |algoa|
330   algo = algoa[0]
331   if conf[algo]==nil
332     puts("No test-set defined for #{algo} \r\n")
333     next
334   else
335         i=0
336         i = opts["j"] if opts["j"]
337         logfile=File.open(conf["PORT"]["testlogbase"]+algo+".txt", "a")
338         while conf[algo]["file_#{i}"] != nil
339           puts("Testing #{algo} with #{conf[algo]["file_#{i}"]}")
340           reset_system()
341           init_system(algoa[1], (conf[algo]["file_#{i}_test"]=='gen')?'1':'2')
342           skip=0
343           skip=opts["i"].to_i if opts["i"]
344     nerrors=run_test_gen(conf[algo]["file_#{i}"], skip) if conf[algo]["file_#{i}_test"]=='gen'
345     nerrors=run_test_ver(conf[algo]["file_#{i}"], skip) if conf[algo]["file_#{i}_test"]=='ver'
346             if nerrors == 0
347         puts("\n[ok]")
348         logfile.puts("[ok] "+conf[algo]["file_#{i}"]+ " ("+Time.now.to_s()+")")
349       else
350         puts("\n[errors: "+ nerrors.to_s() +"]")
351         logfile.puts("[error] "+nerrors.to_s+" "+conf[algo]["file_#{i}"]+ " ("+Time.now.to_s()+")")
352       end
353       i += 1
354     end
355     logfile.close()
356   end
357 end
358
359