0e0a1aa6f71fd9eccb85e45d10233ae28dcc4c0d
[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,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             count=r[2];
101             if count==0:
102                 try: oldmax=maxes[t];
103                 except: oldmax=-1;
104                 if v>oldmax: maxes[t]=v;
105             elif count==1:
106                 try: oldmin=mins[t];
107                 except: oldmin=0x10000;
108                 if v<oldmin: mins[t]=v;
109         print "List complete.  Inserting.";
110         for t in maxes:
111             max=maxes[t];
112             try: min=mins[t];
113             except: min=0;
114             self.db.execute("insert into glitchrange(time,max,min) values (?,?,?)",(t,max,min));
115         self.db.commit();
116         print "Done, database crunched.";
117     def graphx11(self):
118         try:
119             import Gnuplot, Gnuplot.PlotItems, Gnuplot.funcutils
120         except ImportError:
121             print "gnuplot-py is missing.  Can't graph."
122             return;
123         g = Gnuplot.Gnuplot(debug=1);
124         g.clear();
125         
126         g.title('Glitch Training Set');
127         g.xlabel('Time (16MHz)');
128         g.ylabel('VCC (DAC12)');
129         
130         g('set datafile separator "|"');
131         
132         g(script_timevcc);
133         print "^C to exit.";
134         while 1==1:
135             time.sleep(30);
136     def graph(self):
137         import Gnuplot, Gnuplot.PlotItems, Gnuplot.funcutils
138         g = Gnuplot.Gnuplot(debug=1);
139         
140         g('\nset term png');
141         g.title('Glitch Training Set');
142         g.xlabel('Time (16MHz)');
143         g.ylabel('VCC (DAC12)');
144         
145         g('set datafile separator "|"');
146         g('set term png');
147         g('set output "timevcc.png"');
148         g(script_timevcc);
149     def points(self):
150         c=self.db.cursor();
151         c.execute("select time,vcc,gnd,glitchcount,count from glitches where lock=0 and count>0;");
152         print "time vcc gnd glitchcount count";
153         for r in c:
154             print "%i %i %i %i %i" % r;
155     def npoints(self):
156         c=self.db.cursor();
157         c.execute("select time,vcc,gnd,glitchcount,count from glitches where lock=0 and glitchcount>0;");
158         print "time vcc gnd glitchcount count";
159         for r in c:
160             print "%i %i %i %i %i" % r;
161     #GnuPlot sucks for large sets.  Switch to viewpoints soon.
162     # sqlite3 glitch.db "select time,vcc,count from glitches where count=0" | vp -l -d "|" -I
163     
164     def explore(self,tstart=0,tstop=-1, trials=1):
165         """Exploration phase.  Uses thresholds to find exploitable points."""
166         gnd=0;
167         self.scansetup(1); #Lock the chip, place key in eeprom.
168         if tstop<0:
169             tstop=self.client.glitchstarttime();
170         times=range(tstart,tstop);
171         random.shuffle(times);
172         #self.crunch();
173         count=0.0;
174         total=1.0*len(times);
175         
176         c=self.db.cursor();
177         c.execute("select time,min,max from glitchrange where max-min>0;");
178         rows=c.fetchall();
179         c.close();
180         random.shuffle(rows);
181         for r in rows:
182             t=r[0];
183             min=r[1];
184             max=r[2];
185             voltages=range(min,max,1);
186             count=count+1.0;
187             print "%02.02f Exploring %04i points in t=%04i." % (count/total,len(voltages),t);
188             sys.stdout.flush();
189             for vcc in voltages:
190                 self.scanat(1,trials,vcc,gnd,t);
191     def learn(self):
192         """Learning phase.  Finds thresholds at which the chip screws up."""
193         trials=30;
194         lock=0;  #1 locks, 0 unlocked
195         vstart=0;
196         vstop=200;  #Could be as high as 0xFFF, but upper range is useless
197         vstep=1;
198         tstart=0;
199         tstop=self.client.glitchstarttime();
200         tstep=0x1; #Must be 1
201         self.scan(lock,trials,range(vstart,vstop),range(tstart,tstop));
202         print "Learning phase complete, beginning to crunch.";
203         self.crunch();
204         print "Crunch phase complete, beginning to explore.";
205         self.explore();
206         
207     def scansetup(self,lock):
208         client=self.client;
209         client.verbose=0;
210         client.start();
211         client.erase();
212         print "Scanning %s" % client.infostring();
213         
214         self.secret=0x49;
215         
216         while(client.getsecret()!=self.secret):
217             print "-- Setting secret";
218             client.start();
219             
220             #Flash the secret to the first two bytes of CODE memory.
221             client.erase();
222             print "-- Secret was %02x" % client.getsecret();
223             client.setsecret(self.secret);
224             sys.stdout.flush()
225             
226         #Lock chip to unlock it later.
227         if lock>0:
228             client.lock();
229         
230
231     def scan(self,lock,trials,voltages,times):
232         """Scan many voltages and times."""
233         client=self.client;
234         self.scansetup(lock);
235         gnd=0;
236         random.shuffle(voltages);
237         #random.shuffle(times);
238         
239         for vcc in voltages:
240             if not self.vccexplored(vcc):
241                 print "Exploring vcc=%i" % vcc;
242                 sys.stdout.flush();
243                 for time in times:
244                     self.scanat(lock,trials,vcc,gnd,time)
245                     sys.stdout.flush()
246                 self.db.commit();
247             else:
248                 print "Voltage %i already explored." % vcc;
249                 sys.stdout.flush();
250  
251  
252     def vccexplored(self,vcc):
253         c=self.db.cursor();
254         c.execute("select vcc from glitches where vcc=? limit 1;",[vcc]);
255         rows=c.fetchall();
256         for a in rows:
257             return True;
258         c.close();
259         return False; 
260     def scanat(self,lock,trials,vcc,gnd,time):
261         client=self.client;
262         client.glitchRate(time);
263         client.glitchVoltages(gnd, vcc);  #drop voltage target
264         gcount=0;
265         scount=0;
266         #print "-- (%5i,%5i)" % (time,vcc);
267         #sys.stdout.flush();
268         for i in range(0,trials):
269             client.glitchstart();
270             
271             #Try to read *0, which is secret if read works.
272             a=client.getsecret();
273             if lock>0: #locked
274                 if(a!=0 and a!=0xFF and a!=self.secret):
275                     gcount+=1;
276                 if(a==self.secret):
277                     print "-- %06i: %02x HELL YEAH! " % (time, a);
278                     scount+=1;
279             else: #unlocked
280                 if(a!=self.secret):
281                     gcount+=1;
282                 if(a==self.secret):
283                     scount+=1;
284         #print "values (%i,%i,%i,%i,%i);" % (
285         #    time,vcc,gnd,gcount,scount);
286         if(lock==0):
287             self.db.execute("insert into glitches(time,vcc,gnd,trials,glitchcount,count,lock)"
288                    "values (%i,%i,%i,%i,%i,%i,%i);" % (
289                 time,vcc,gnd,trials,gcount,scount,lock));
290         elif scount>0:
291             print "INSERTING AN EXPLOIT point, t=%i and vcc=%i" % (time,vcc);
292             self.db.execute("insert into exploits(time,vcc,gnd,trials,count)"
293                    "values (%i,%i,%i,%i,%i);" % (
294                 time,vcc,gnd,trials,scount));
295             self.db.commit(); #Don't leave a lock open.