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