Python library and plaything for ARM JTAG
[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 class GoodFETGlitch(GoodFET):
26     
27     def __init__(self, *args, **kargs):
28         print "Initializing GoodFET Glitcher."
29         #Database connection w/ 30 second timeout.
30         self.db=sqlite3.connect("glitch.db",30000);
31         self.db.execute("create table if not exists glitches(time,vcc,gnd,trials,glitchcount,count,lock)");
32         self.client=0;
33     def setup(self,arch="avr"):
34         self.client=getClient(arch);
35     def graphx11(self):
36         try:
37             import Gnuplot, Gnuplot.PlotItems, Gnuplot.funcutils
38         except ImportError:
39             print "gnuplot-py is missing.  Can't graph."
40             return;
41         g = Gnuplot.Gnuplot(debug=1);
42         g.clear();
43         
44         g.title('Glitch Training Set');
45         g.xlabel('Time (16MHz)');
46         g.ylabel('VCC (DAC12)');
47         
48         g('set datafile separator "|"');
49         
50         g(script_timevcc);
51         while 1==1:
52             time.sleep(30);
53             g('replot');
54
55         
56     def graph(self):
57         #try:
58         import Gnuplot, Gnuplot.PlotItems, Gnuplot.funcutils
59         #except ImportError:
60         #    print "py-gnuplot or py-numpy is missing.  Can't graph."
61         #    return;
62         g = Gnuplot.Gnuplot(debug=1);
63         
64         g('\nset term png');
65         g.title('Glitch Training Set');
66         g.xlabel('Time (16MHz)');
67         g.ylabel('VCC (DAC12)');
68         
69         g('set datafile separator "|"');
70         g('set term png');
71         g('set output "timevcc.png"');
72         g(script_timevcc);
73         
74     def learn(self):
75         #Learning phase
76         trials=1;
77         lock=0;  #1 locks, 0 unlocked
78         vstart=0;
79         vstop=1024;  #Could be as high as 0xFFF
80         vstep=1;
81         tstart=0;
82         tstop=-1; #<0 defaults to full range
83         tstep=0x1; #Must be 1
84         self.scan(lock,trials,vstart,vstop,tstart,tstop);
85
86     def scan(self,lock,trials=1,vstart=0,vstop=0xfff,tstart=0,tstop=-1):
87         client=self.client;
88         self.lock=lock;
89         client.serInit();
90         if tstop<0:
91             tstop=client.glitchstarttime();  #Really long; only use for initial investigation.
92             print "-- Start takes %04i cycles." % tstop;
93         client.start();
94         client.erase();
95         
96         self.secret=0x69;
97
98         while(client.eeprompeek(0)!=self.secret):
99             print "-- Setting secret";
100             client.start();
101             
102             #Flash the secret to the first two bytes of CODE memory.
103             client.erase();
104             client.eeprompoke(0,self.secret);
105             client.eeprompoke(1,self.secret);
106             sys.stdout.flush()
107
108         #Lock chip to unlock it later.
109         if lock>0:
110             client.lock();
111         voltages=range(vstart,vstop,1);
112         times=range(tstart,tstop,1);
113         
114         gnd=0;     #TODO, glitch GND.
115         vcc=0xfff;
116         random.shuffle(voltages);
117         #random.shuffle(times);
118         
119         for vcc in voltages:
120             if not self.vccexplored(vcc):
121                 print "Exploring vcc=%i" % vcc;
122                 sys.stdout.flush();
123                 for time in times:
124                     self.scanat(trials,vcc,gnd,time)
125                     sys.stdout.flush()
126                 self.db.commit();
127             else:
128                 print "Voltage %i already explored." % vcc;
129                 sys.stdout.flush();
130     def vccexplored(self,vcc):
131         c=self.db.cursor();
132         c.execute("select vcc from glitches where vcc=? limit 1;",[vcc]);
133         rows=c.fetchall();
134         try:
135             c.next(); 
136             #This voltage has been explored, because no complete exception has been thrown.
137             return True;
138         except: #Voltage hasn't been explored
139             return False;
140         
141     def scanat(self,trials,vcc,gnd,time):
142         client=self.client;
143         db=self.db;
144         client.glitchRate(time);
145         client.glitchVoltages(gnd, vcc);  #drop voltage target
146         gcount=0;
147         scount=0;
148         #print "-- (%5i,%5i)" % (time,vcc);
149         #sys.stdout.flush();
150         for i in range(0,trials):
151             client.glitchstart();
152             
153             #Try to read *0, which is secret if read works.
154             a=client.eeprompeek(0x0);
155             if self.lock>0: #locked
156                 if(a!=0 and a!=0xFF and a!=self.secret):
157                     gcount+=1;
158                 if(a==self.secret):
159                     print "-- %04x: %02x HELL YEAH! " % (time, a);
160                     scount+=1;
161             else: #unlocked
162                 if(a!=self.secret):
163                     gcount+=1;
164                 if(a==self.secret):
165                     scount+=1;
166         #print "values (%i,%i,%i,%i,%i);" % (
167         #    time,vcc,gnd,gcount,scount);
168         self.db.execute("insert into glitches(time,vcc,gnd,trials,glitchcount,count,lock)"
169                    "values (%i,%i,%i,%i,%i,%i,%i);" % (
170                 time,vcc,gnd,trials,gcount,scount,self.lock));