my play thing update.
[goodfet] / client / GoodFETGlitch.py
1 #!/usr/bin/env python
2 # GoodFET Client Library
3
4 # (C) 2009 Travis Goodspeed <travis at radiantmachines.com>
5 #
6 # This code is being rewritten and refactored.  You've been warned!
7
8 import sys, time, string, cStringIO, struct, glob, serial, os, random;
9 import sqlite3;
10
11 from GoodFET import *;
12
13 script_timevcc="""
14 plot "< sqlite3 glitch.db 'select time,vcc,glitchcount from glitches where count=0;'" \
15 with dots \
16 title "Scanned", \
17 "< sqlite3 glitch.db 'select time,vcc,count from glitches where count>0;'" \
18 with dots \
19 title "Success", \
20 "< sqlite3 glitch.db 'select time,vcc,count from glitches where count>0 and lock>0;'" \
21 with dots \
22 title "Exploited"
23 """;
24
25 script_timevccrange="""
26 plot "< sqlite3 glitch.db 'select time,vcc,glitchcount from glitches where count=0;'" \
27 with dots \
28 title "Scanned", \
29 "< sqlite3 glitch.db 'select time,vcc,count from glitches where count>0;'" \
30 with dots \
31 title "Success", \
32 "< sqlite3 glitch.db 'select time,max(vcc),count from glitches where count=0 group by time ;'" with lines title "Max", \
33 "< sqlite3 glitch.db 'select time,min(vcc),count from glitches where count>0 group by time ;'" with lines title "Min"
34 """;
35
36 class GoodFETGlitch(GoodFET):
37     
38     def __init__(self, *args, **kargs):
39         print "Initializing GoodFET Glitcher."
40         #Database connection w/ 30 second timeout.
41         self.db=sqlite3.connect("glitch.db",30000);
42         self.db.execute("create table if not exists glitches(time,vcc,gnd,trials,glitchcount,count,lock)");
43         self.db.execute("create index if not exists glitchvcc on glitches(vcc);");
44         self.db.execute("create index if not exists glitchtime on glitches(time);");
45         self.client=0;
46     def setup(self,arch="avr"):
47         self.client=getClient(arch);
48     def graphx11(self):
49         try:
50             import Gnuplot, Gnuplot.PlotItems, Gnuplot.funcutils
51         except ImportError:
52             print "gnuplot-py is missing.  Can't graph."
53             return;
54         g = Gnuplot.Gnuplot(debug=1);
55         g.clear();
56         
57         g.title('Glitch Training Set');
58         g.xlabel('Time (16MHz)');
59         g.ylabel('VCC (DAC12)');
60         
61         g('set datafile separator "|"');
62         
63         g(script_timevcc);
64         print "^C to exit.";
65         while 1==1:
66             time.sleep(30);
67         #    g('replot');
68
69         
70     def graph(self):
71         #try:
72         import Gnuplot, Gnuplot.PlotItems, Gnuplot.funcutils
73         #except ImportError:
74         #    print "py-gnuplot or py-numpy is missing.  Can't graph."
75         #    return;
76         g = Gnuplot.Gnuplot(debug=1);
77         
78         g('\nset term png');
79         g.title('Glitch Training Set');
80         g.xlabel('Time (16MHz)');
81         g.ylabel('VCC (DAC12)');
82         
83         g('set datafile separator "|"');
84         g('set term png');
85         g('set output "timevcc.png"');
86         g(script_timevcc);
87         
88     def learn(self):
89         #Learning phase
90         trials=1;
91         lock=0;  #1 locks, 0 unlocked
92         vstart=0;
93         vstop=0xfff;  #Could be as high as 0xFFF
94         vstep=1;
95         tstart=0;
96         tstop=-1; #<0 defaults to full range
97         tstep=0x1; #Must be 1
98         self.scan(lock,trials,vstart,vstop,tstart,tstop);
99
100     def scan(self,lock,trials=1,vstart=0,vstop=0xfff,tstart=0,tstop=-1):
101         client=self.client;
102         self.lock=lock;
103         client.serInit();
104         if tstop<0:
105             tstop=client.glitchstarttime();  #Really long; only use for initial investigation.
106             print "-- Start takes %04i cycles." % tstop;
107         client.start();
108         client.erase();
109         
110         self.secret=0x69;
111
112         while(client.eeprompeek(0)!=self.secret):
113             print "-- Setting secret";
114             client.start();
115             
116             #Flash the secret to the first two bytes of CODE memory.
117             client.erase();
118             client.eeprompoke(0,self.secret);
119             client.eeprompoke(1,self.secret);
120             sys.stdout.flush()
121
122         #Lock chip to unlock it later.
123         if lock>0:
124             client.lock();
125         voltages=range(vstart,vstop,1);
126         times=range(tstart,tstop,1);
127         
128         gnd=0;     #TODO, glitch GND.
129         vcc=0xfff;
130         random.shuffle(voltages);
131         #random.shuffle(times);
132         
133         for vcc in voltages:
134             if not self.vccexplored(vcc):
135                 print "Exploring vcc=%i" % vcc;
136                 sys.stdout.flush();
137                 for time in times:
138                     self.scanat(trials,vcc,gnd,time)
139                     sys.stdout.flush()
140                 self.db.commit();
141             else:
142                 print "Voltage %i already explored." % vcc;
143                 sys.stdout.flush();
144     def vccexplored(self,vcc):
145         c=self.db.cursor();
146         c.execute("select vcc from glitches where vcc=? limit 1;",[vcc]);
147         rows=c.fetchall();
148         for a in rows:
149             return True;
150         return False; 
151     def scanat(self,trials,vcc,gnd,time):
152         client=self.client;
153         db=self.db;
154         client.glitchRate(time);
155         client.glitchVoltages(gnd, vcc);  #drop voltage target
156         gcount=0;
157         scount=0;
158         #print "-- (%5i,%5i)" % (time,vcc);
159         #sys.stdout.flush();
160         for i in range(0,trials):
161             client.glitchstart();
162             
163             #Try to read *0, which is secret if read works.
164             a=client.eeprompeek(0x0);
165             if self.lock>0: #locked
166                 if(a!=0 and a!=0xFF and a!=self.secret):
167                     gcount+=1;
168                 if(a==self.secret):
169                     print "-- %04x: %02x HELL YEAH! " % (time, a);
170                     scount+=1;
171             else: #unlocked
172                 if(a!=self.secret):
173                     gcount+=1;
174                 if(a==self.secret):
175                     scount+=1;
176         #print "values (%i,%i,%i,%i,%i);" % (
177         #    time,vcc,gnd,gcount,scount);
178         self.db.execute("insert into glitches(time,vcc,gnd,trials,glitchcount,count,lock)"
179                    "values (%i,%i,%i,%i,%i,%i,%i);" % (
180                 time,vcc,gnd,trials,gcount,scount,self.lock));