Fixed 2500kbps rate.
[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
14 # After four million points, this kills 32-bit gnuplot.
15 # Dumping to a bitmap might be preferable.
16 script_timevcc="""
17 plot "< sqlite3 glitch.db 'select time,vcc,glitchcount from glitches where count=0;'" \
18 with dots \
19 title "Scanned", \
20 "< sqlite3 glitch.db 'select time,vcc,count from glitches where count>0;'" \
21 with dots \
22 title "Success", \
23 "< sqlite3 glitch.db 'select time,vcc,count from glitches where count>0 and lock>0;'" \
24 with dots \
25 title "Exploited"
26 """;
27 script_timevccrange="""
28 plot "< sqlite3 glitch.db 'select time,vcc,glitchcount from glitches where count=0;'" \
29 with dots \
30 title "Scanned", \
31 "< sqlite3 glitch.db 'select time,vcc,count from glitches where count>0;'" \
32 with dots \
33 title "Success", \
34 "< sqlite3 glitch.db 'select time,max(vcc),count from glitches where count=0 group by time ;'" with lines title "Max", \
35 "< sqlite3 glitch.db 'select time,min(vcc),count from glitches where count>0 group by time ;'" with lines title "Min"
36 """;
37
38 class GoodFETGlitch(GoodFET):
39     
40     def __init__(self, *args, **kargs):
41         print "# Initializing GoodFET Glitcher."
42         #Database connection w/ 30 second timeout.
43         self.db=sqlite3.connect("glitch.db",30000);
44         
45         #Training
46         self.db.execute("create table if not exists glitches(time,vcc,gnd,trials,glitchcount,count,lock);");
47         self.db.execute("create index if not exists glitchvcc on glitches(vcc);");
48         self.db.execute("create index if not exists glitchtime on glitches(time);");
49         
50         #Exploitation record, to be built from the training table.
51         self.db.execute("create table if not exists exploits(time,vcc,gnd,trials,count);");
52         self.db.execute("create index if not exists exploitvcc on exploits(vcc);");
53         self.db.execute("create index if not exists exploittime on exploits(time);");
54         
55         self.client=0;
56     def setup(self,arch="avr"):
57         self.client=getClient(arch);
58         self.client.serInit(); #No timeout
59
60     def glitchvoltages(self,time):
61         """Returns list of voltages to train at."""
62         c=self.db.cursor();
63         #c.execute("""select
64         #             (select min(vcc) from glitches where time=? and count=1),
65         #             (select max(vcc) from glitches where time=? and count=0);""",
66         #          [time, time]);
67         c.execute("select min,max from glitchrange where time=? and max-min>0;",[time]);
68         rows=c.fetchall();
69         for r in rows:
70             min=r[0];
71             max=r[1];
72             if(min==None or max==None): return [];
73             
74             spread=max-min;
75             return range(min,max,1);
76         #If we get here, there are no points.  Return empty set.
77         return [];
78     def crunch(self):
79         """This builds tables for glitching voltage ranges from the training set."""
80         print "Precomputing glitching ranges.  This might take a long while.";
81         print "Times...";
82         sys.stdout.flush();
83         self.db.execute("drop table if exists glitchrange;");
84         self.db.execute("create table glitchrange(time integer primary key asc,max,min);");
85         self.db.commit();
86         print "Calculating ranges...";
87         sys.stdout.flush();
88         
89         maxes={};
90         mins={};
91         
92         c=self.db.cursor();
93         c.execute("select time,vcc,glitchcount,count from glitches;"); #Limit 10000 for testing.
94         progress=0;
95         for r in c:
96             progress=progress+1;
97             if progress % 1000000==0: print "%09i rows crunched." % progress;
98             t=r[0];
99             v=r[1];
100             glitchcount=r[2];
101             count=r[3];
102             # FIXME: Threse thresholds suck.
103             if count<2:
104                 try: oldmax=maxes[t];
105                 except: oldmax=-1;
106                 if v>oldmax: maxes[t]=v;
107             elif glitchcount<2:
108                 try: oldmin=mins[t];
109                 except: oldmin=0x10000;
110                 if v<oldmin: mins[t]=v;
111         print "List complete.  Inserting.";
112         for t in maxes:
113             max=maxes[t];
114             try: min=mins[t];
115             except: min=0;
116             self.db.execute("insert into glitchrange(time,max,min) values (?,?,?)",(t,max,min));
117         self.db.commit();
118         print "Done, database crunched.";
119     def graphx11(self):
120         try:
121             import Gnuplot, Gnuplot.PlotItems, Gnuplot.funcutils
122         except ImportError:
123             print "gnuplot-py is missing.  Can't graph."
124             return;
125         g = Gnuplot.Gnuplot(debug=1);
126         g.clear();
127         
128         g.title('Glitch Training Set');
129         g.xlabel('Time (16MHz)');
130         g.ylabel('VCC (DAC12)');
131         
132         g('set datafile separator "|"');
133         
134         g(script_timevcc);
135         print "^C to exit.";
136         while 1==1:
137             time.sleep(30);
138     def graph(self):
139         import Gnuplot, Gnuplot.PlotItems, Gnuplot.funcutils
140         g = Gnuplot.Gnuplot(debug=1);
141         
142         g('\nset term png');
143         g.title('Glitch Training Set');
144         g.xlabel('Time (16MHz)');
145         g.ylabel('VCC (DAC12)');
146         
147         g('set datafile separator "|"');
148         g('set term png');
149         g('set output "timevcc.png"');
150         g(script_timevcc);
151     def points(self):
152         c=self.db.cursor();
153         c.execute("select time,vcc,gnd,glitchcount,count from glitches where lock=0 and glitchcount>0;");
154         print "time vcc gnd glitchcount count";
155         for r in c:
156             print "%i %i %i %i %i" % r;
157     def rpoints(self):
158         c=self.db.cursor();
159         c.execute("select time,vcc,gnd,glitchcount,count from glitches where lock=0 and glitchcount>0;");
160         print "time vcc gnd glitchcount count";
161         for r in c:
162             print "%i %i %i %i %i" % r;
163     #GnuPlot sucks for large sets.  Switch to viewpoints soon.
164     # sqlite3 glitch.db "select time,vcc,count from glitches where count=0" | vp -l -d "|" -I
165     
166     def explore(self,times=None, trials=10):
167         """Exploration phase.  Uses thresholds to find exploitable points."""
168         gnd=0;
169         self.scansetup(1); #Lock the chip, place key in eeprom.
170         if times==None:
171             tstart=0;
172             tstop=self.client.glitchstarttime();
173             times=range(tstart,tstop);
174         random.shuffle(times);
175         #self.crunch();
176         count=0.0;
177         total=1.0*len(times);
178         
179         c=self.db.cursor();
180         c.execute("select time,min,max from glitchrange where max-min>0;");
181         rows=c.fetchall();
182         c.close();
183         random.shuffle(rows);
184         print "Exploring %i times." % len(times);
185         mins={};
186         maxes={};
187         for r in rows:
188             t=r[0];
189             mins[t]=r[1];
190             maxes[t]=r[2];
191         for t in times:
192             min=mins[t];
193             max=maxes[t];
194             voltages=range(min,max,1);
195             count=count+1.0;
196             print "%02.02f Exploring %04i points in t=%04i." % (count/total,len(voltages),t);
197             sys.stdout.flush();
198             for vcc in voltages:
199                 self.scanat(1,trials,vcc,gnd,t);
200     def learn(self):
201         """Learning phase.  Finds thresholds at which the chip screws up."""
202         trials=30;
203         lock=0;  #1 locks, 0 unlocked
204         vstart=0;
205         vstop=1024;  #Could be as high as 0xFFF, but upper range is useless
206         vstep=1;
207         tstart=0;
208         tstop=self.client.glitchstarttime();
209         tstep=0x1; #Must be 1
210         self.scan(lock,trials,range(vstart,vstop),range(tstart,tstop));
211         print "Learning phase complete, beginning to crunch.";
212         self.crunch();
213         print "Crunch phase complete, beginning to explore.";
214         self.explore();
215         
216     def scansetup(self,lock):
217         client=self.client;
218         client.verbose=0;
219         client.start();
220         client.erase();
221         print "Scanning %s" % client.infostring();
222         
223         self.secret=0x49;
224         
225         while(client.getsecret()!=self.secret):
226             print "-- Setting secret";
227             client.start();
228             
229             #Flash the secret to the first two bytes of CODE memory.
230             client.erase();
231             print "-- Secret was %02x" % client.getsecret();
232             client.setsecret(self.secret);
233             sys.stdout.flush()
234             
235         #Lock chip to unlock it later.
236         if lock>0:
237             client.lock();
238         
239
240     def scan(self,lock,trials,voltages,times):
241         """Scan many voltages and times."""
242         client=self.client;
243         self.scansetup(lock);
244         gnd=0;
245         random.shuffle(voltages);
246         #random.shuffle(times);
247         
248         for vcc in voltages:
249             if not self.vccexplored(vcc):
250                 print "Exploring vcc=%i" % vcc;
251                 sys.stdout.flush();
252                 for time in times:
253                     self.scanat(lock,trials,vcc,gnd,time)
254                     sys.stdout.flush()
255                 self.db.commit();
256             else:
257                 print "Voltage %i already explored." % vcc;
258                 sys.stdout.flush();
259  
260  
261     def vccexplored(self,vcc):
262         c=self.db.cursor();
263         c.execute("select vcc from glitches where vcc=? limit 1;",[vcc]);
264         rows=c.fetchall();
265         for a in rows:
266             return True;
267         c.close();
268         return False; 
269     def scanat(self,lock,trials,vcc,gnd,time):
270         client=self.client;
271         client.glitchRate(time);
272         client.glitchVoltages(gnd, vcc);  #drop voltage target
273         gcount=0;
274         scount=0;
275         #print "-- (%5i,%5i)" % (time,vcc);
276         #sys.stdout.flush();
277         for i in range(0,trials):
278             client.glitchstart();
279             
280             #Try to read *0, which is secret if read works.
281             a=client.getsecret();
282             if lock>0: #locked
283                 if(a!=0 and a!=0xFF and a!=self.secret):
284                     gcount+=1;
285                 if(a==self.secret):
286                     print "-- %06i: %02x HELL YEAH! " % (time, a);
287                     scount+=1;
288             else: #unlocked
289                 if(a!=self.secret):
290                     gcount+=1;
291                 if(a==self.secret):
292                     scount+=1;
293         #print "values (%i,%i,%i,%i,%i);" % (
294         #    time,vcc,gnd,gcount,scount);
295         if(lock==0):
296             self.db.execute("insert into glitches(time,vcc,gnd,trials,glitchcount,count,lock)"
297                    "values (%i,%i,%i,%i,%i,%i,%i);" % (
298                 time,vcc,gnd,trials,gcount,scount,lock));
299         elif scount>0:
300             print "INSERTING AN EXPLOIT point, t=%i and vcc=%i" % (time,vcc);
301             self.db.execute("insert into exploits(time,vcc,gnd,trials,count)"
302                    "values (%i,%i,%i,%i,%i);" % (
303                 time,vcc,gnd,trials,scount));
304             self.db.commit(); #Don't leave a lock open.