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