2e0b2b42751df9fce835c3902ee54bbf3a09c729
[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();
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.execute("insert into glitchrange(time,max,min) select distinct time, 0, 0 from glitches;");
86         print "Maximums...";
87         sys.stdout.flush();
88         self.db.execute("update glitchrange set max=(select max(vcc) from glitches where glitches.time=glitchrange.time and count=0);");
89         print "Minimums...";
90         sys.stdout.flush();
91         self.db.execute("update glitchrange set min=(select min(vcc) from glitches where glitches.time=glitchrange.time and count>0);");
92         print "Ranges calculated.";
93     def graphx11(self):
94         try:
95             import Gnuplot, Gnuplot.PlotItems, Gnuplot.funcutils
96         except ImportError:
97             print "gnuplot-py is missing.  Can't graph."
98             return;
99         g = Gnuplot.Gnuplot(debug=1);
100         g.clear();
101         
102         g.title('Glitch Training Set');
103         g.xlabel('Time (16MHz)');
104         g.ylabel('VCC (DAC12)');
105         
106         g('set datafile separator "|"');
107         
108         g(script_timevcc);
109         print "^C to exit.";
110         while 1==1:
111             time.sleep(30);
112
113         
114     def graph(self):
115         import Gnuplot, Gnuplot.PlotItems, Gnuplot.funcutils
116         g = Gnuplot.Gnuplot(debug=1);
117         
118         g('\nset term png');
119         g.title('Glitch Training Set');
120         g.xlabel('Time (16MHz)');
121         g.ylabel('VCC (DAC12)');
122         
123         g('set datafile separator "|"');
124         g('set term png');
125         g('set output "timevcc.png"');
126         g(script_timevcc);
127     def explore(self,tstart=0,tstop=-1, trials=5):
128         """Exploration phase.  Uses thresholds to find exploitable points."""
129         gnd=0;
130         self.scansetup(1); #Lock the chip, place key in eeprom.
131         if tstop<0:
132             tstop=self.client.glitchstarttime();
133         times=range(tstart,tstop);
134         random.shuffle(times);
135         #self.crunch();
136         count=0.0;
137         total=1.0*len(times);
138         for t in times:
139             voltages=self.glitchvoltages(t);
140             count=count+1.0;
141             print "%02.02f Exploring %04i points in t=%04i." % (count/total,len(voltages),t);
142             sys.stdout.flush();
143             for vcc in voltages:
144                 self.scanat(1,trials,vcc,gnd,t);
145     def learn(self):
146         """Learning phase.  Finds thresholds at which the chip screws up."""
147         trials=1;
148         lock=0;  #1 locks, 0 unlocked
149         vstart=0;
150         vstop=1024;  #Could be as high as 0xFFF, but upper range is useless
151         vstep=1;
152         tstart=0;
153         tstop=self.client.glitchstarttime();
154         tstep=0x1; #Must be 1
155         self.scan(lock,trials,range(vstart,vstop),range(tstart,tstop));
156         print "Learning phase complete, beginning to expore.";
157         self.explore();
158         
159     def scansetup(self,lock):
160         client=self.client;
161         client.start();
162         client.erase();
163         
164         self.secret=0x69;
165         
166         while(client.eeprompeek(0)!=self.secret):
167             print "-- Setting secret";
168             client.start();
169             
170             #Flash the secret to the first two bytes of CODE memory.
171             client.erase();
172             client.eeprompoke(0,self.secret);
173             client.eeprompoke(1,self.secret);
174             sys.stdout.flush()
175
176         #Lock chip to unlock it later.
177         if lock>0:
178             client.lock();
179         
180
181     def scan(self,lock,trials,voltages,times):
182         """Scan many voltages and times."""
183         client=self.client;
184         self.scansetup(lock);
185         gnd=0;
186         random.shuffle(voltages);
187         #random.shuffle(times);
188         
189         for vcc in voltages:
190             if lock<0 and not self.vccexplored(vcc):
191                 print "Exploring vcc=%i" % vcc;
192                 sys.stdout.flush();
193                 for time in times:
194                     self.scanat(lock,trials,vcc,gnd,time)
195                     sys.stdout.flush()
196                 self.db.commit();
197             else:
198                 print "Voltage %i already explored." % vcc;
199                 sys.stdout.flush();
200  
201  
202     def vccexplored(self,vcc):
203         c=self.db.cursor();
204         c.execute("select vcc from glitches where vcc=? limit 1;",[vcc]);
205         rows=c.fetchall();
206         for a in rows:
207             return True;
208         return False; 
209     def scanat(self,lock,trials,vcc,gnd,time):
210         client=self.client;
211         db=self.db;
212         client.glitchRate(time);
213         client.glitchVoltages(gnd, vcc);  #drop voltage target
214         gcount=0;
215         scount=0;
216         #print "-- (%5i,%5i)" % (time,vcc);
217         #sys.stdout.flush();
218         for i in range(0,trials):
219             client.glitchstart();
220             
221             #Try to read *0, which is secret if read works.
222             a=client.eeprompeek(0x0);
223             if lock>0: #locked
224                 if(a!=0 and a!=0xFF and a!=self.secret):
225                     gcount+=1;
226                 if(a==self.secret):
227                     print "-- %06i: %02x HELL YEAH! " % (time, a);
228                     scount+=1;
229             else: #unlocked
230                 if(a!=self.secret):
231                     gcount+=1;
232                 if(a==self.secret):
233                     scount+=1;
234         #print "values (%i,%i,%i,%i,%i);" % (
235         #    time,vcc,gnd,gcount,scount);
236         if(lock>0):
237             self.db.execute("insert into glitches(time,vcc,gnd,trials,glitchcount,count,lock)"
238                    "values (%i,%i,%i,%i,%i,%i,%i);" % (
239                 time,vcc,gnd,trials,gcount,scount,lock));
240         else:
241             self.db.execute("insert into exploits(time,vcc,gnd,trials,count)"
242                    "values (%i,%i,%i,%i,%i);" % (
243                 time,vcc,gnd,trials,scount));