snippets
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

257 lines
9.0 KiB

3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
  1. import logging
  2. import random
  3. logger = logging.getLogger(__name__)
  4. import h5py
  5. import matplotlib.pyplot as plt
  6. import numpy
  7. import scipy.fft
  8. import scipy.signal
  9. import tqdm
  10. # import opt_einsum
  11. import numpy_popcount
  12. AES_SBOX = numpy.array([
  13. # 0 1 2 3 4 5 6 7 8 9 A B C D E F
  14. 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
  15. 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
  16. 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
  17. 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
  18. 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
  19. 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
  20. 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
  21. 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
  22. 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
  23. 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
  24. 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
  25. 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
  26. 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
  27. 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
  28. 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
  29. 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
  30. ], dtype='uint8')
  31. def align(db, ntraces):
  32. logger.info("aligning traces")
  33. traces = db["traces"]
  34. reference = traces[0].astype("double")
  35. alignments = numpy.zeros(ntraces, "int64")
  36. lags = scipy.signal.correlation_lags(len(reference), len(reference))
  37. for i in tqdm.trange(1, ntraces):
  38. trace = traces[i].astype("double")
  39. corr = scipy.signal.correlate(reference, trace)
  40. max_idxs = corr.argsort()[-10:][::-1]
  41. max_corr = 0
  42. max_idx = -1
  43. for idx in max_idxs:
  44. lag = lags[idx]
  45. if lag == 0:
  46. s_ref = reference
  47. s_trs = trace
  48. elif lag < 0:
  49. s_ref = reference[:lag]
  50. s_trs = trace[-lag:]
  51. else:
  52. s_ref = reference[lag:]
  53. s_trs = trace[:-lag]
  54. pcorr = numpy.corrcoef(s_ref, s_trs)[1,0]
  55. if pcorr > max_corr:
  56. max_corr = pcorr
  57. max_idx = idx
  58. lag = lags[max_idx]
  59. alignments[i] = lag
  60. alignments -= numpy.min(alignments)
  61. max_start = max(alignments)
  62. min_end = 700
  63. traces = numpy.zeros((ntraces, 800), 'double')
  64. for i in range(ntraces):
  65. traces[i, alignments[i]:alignments[i]+700] = db["traces"][i]
  66. return traces[:, max_start:min_end]
  67. # P - (n,m) array of n predictions for each of the m candidates
  68. # O - (n,t) array of n traces with t samples each
  69. # returns an (m,t) correlation matrix of m traces t samples each
  70. # TODO : is opt_einsum faster?
  71. class Correlator:
  72. def __init__(self, P):
  73. self.P = P - numpy.mean(P, axis=0)
  74. self.tmp1 = numpy.einsum("nm,nm->m", self.P, self.P, optimize='optimal')
  75. self.P = self.P.transpose()
  76. def corr_submatrix(self, O):
  77. O -= numpy.mean(O, axis=0)
  78. numerator = self.P @ O
  79. tmp2 = numpy.einsum("nt,nt->t", O, O, optimize='optimal')
  80. denominator = numpy.sqrt(numpy.outer(self.tmp1, tmp2))
  81. return numerator / denominator
  82. def attack_firstorder(db, traces, ntraces):
  83. logger.info("making first order model")
  84. model = numpy.repeat(numpy.arange(256, dtype='uint8'), ntraces).reshape((256, ntraces))
  85. for i in tqdm.trange(ntraces):
  86. (pt, ct, key, mask, desync) = db["metadata"][i]
  87. pt_v = pt[2]
  88. mask_v = mask[15]
  89. model[:, i] = AES_SBOX[model[:, i] ^ pt_v] ^ mask_v
  90. model = numpy_popcount.popcount(model).astype("double").transpose()
  91. # boring, slow, uses too much RAM
  92. # input_matrix = numpy.vstack((model, traces.transpose()))
  93. # coefs = numpy.corrcoef(input_matrix)[0:256, 256:]
  94. # uwu
  95. correlator = Correlator(model)
  96. coefs = correlator.corr_submatrix(traces)
  97. # plot absmax
  98. coefs = numpy.abs(coefs)
  99. max_by_key = numpy.max(coefs, axis=1)
  100. plt.plot(max_by_key)
  101. plt.show()
  102. def attack_firstorder_fft(db, traces, ntraces):
  103. # lol
  104. ntraces = 2000
  105. db = h5py.File("./ASCAD_databases/ASCAD_desync100.h5", "r")["Attack_traces"]
  106. traces = db["traces"][0:ntraces, :].astype("double")
  107. logger.info("making first order model")
  108. model = numpy.repeat(numpy.arange(256, dtype='uint8'), ntraces).reshape((256, ntraces))
  109. for i in tqdm.trange(ntraces):
  110. (pt, ct, key, mask, desync) = db["metadata"][i]
  111. pt_v = pt[2]
  112. mask_v = mask[15]
  113. model[:, i] = AES_SBOX[model[:, i] ^ pt_v] ^ mask_v
  114. model = numpy_popcount.popcount(model).astype("double").transpose()
  115. logger.info("making fft traces")
  116. fft_traces = numpy.zeros(traces.shape, traces.dtype)
  117. for i in range(traces.shape[0]):
  118. fft_traces[i, :] = numpy.abs(scipy.fft.fft(traces[i, :]))
  119. traces = fft_traces[:, 1:350]
  120. avg = numpy.mean(traces, axis=0)
  121. peaks = avg.argsort()[-50:][::-1]
  122. traces = numpy.hstack([traces[:, i:i+1] for i in peaks])
  123. correlator = Correlator(model)
  124. coefs = correlator.corr_submatrix(traces)
  125. # plot absmax
  126. coefs = numpy.abs(coefs)
  127. max_by_key = numpy.max(coefs, axis=1)
  128. plt.plot(max_by_key)
  129. plt.show()
  130. # def attack_secondorder_fft(db, traces, ntraces):
  131. # # needs work
  132. # # lol
  133. # ntraces = 10000
  134. # db = h5py.File("./ASCAD_databases/ASCAD.h5", "r")["Attack_traces"]
  135. # traces = db["traces"][0:ntraces, :].astype("double")
  136. #
  137. # logger.info("making second order model")
  138. # model = numpy.repeat(numpy.arange(256, dtype='uint8'), ntraces).reshape((256, ntraces))
  139. # for i in tqdm.trange(ntraces):
  140. # (pt, ct, key, mask, desync) = db["metadata"][i]
  141. # pt_v = pt[2]
  142. # mask_v = mask[15]
  143. # model[:, i] = AES_SBOX[model[:, i] ^ pt_v] ^ mask_v
  144. # model = numpy_popcount.popcount(model).astype("double").transpose()
  145. #
  146. # logger.info("making fft traces")
  147. # fft_traces = numpy.zeros((traces.shape[0], traces.shape[1]), traces.dtype)
  148. # for i in range(traces.shape[0]):
  149. # fft_i = numpy.abs(scipy.fft.fft(traces[i, :]))
  150. # conv_i = numpy.abs(numpy.conj(fft_i) * fft_i)
  151. # fft_traces[i, :] = conv_i
  152. #
  153. # traces = fft_traces
  154. # # traces = fft_traces[:, 1:350]
  155. # # avg = numpy.mean(traces, axis=0)
  156. # # peaks = avg.argsort()[-50:][::-1]
  157. # # traces = numpy.hstack([traces[:, i:i+1] for i in peaks])
  158. #
  159. # correlator = Correlator(model)
  160. # coefs = correlator.corr_submatrix(traces)
  161. #
  162. # # plot absmax
  163. # coefs = numpy.abs(coefs)
  164. # max_by_key = numpy.max(coefs, axis=1)
  165. # plt.plot(max_by_key)
  166. # plt.show()
  167. def attack_secondorder(db, traces, ntraces):
  168. logger.info("making second order model")
  169. model = numpy.repeat(numpy.arange(256, dtype='uint8'), ntraces).reshape((256, ntraces))
  170. for i in tqdm.trange(ntraces):
  171. (pt, ct, key, mask, desync) = db["metadata"][i]
  172. pt_v = pt[2]
  173. model[:, i] = AES_SBOX[model[:, i] ^ pt_v]
  174. model = numpy_popcount.popcount(model).astype("double").transpose()
  175. logger.info("making second order combinations")
  176. nticks = traces.shape[1]
  177. traces_x = numpy.zeros((ntraces, nticks*(nticks - 1)//2), 'double')
  178. tx_i = 0
  179. for i in tqdm.trange(nticks):
  180. for j in range(i+1, nticks):
  181. traces_x[:, tx_i] = numpy.abs(traces[:, i] - traces[:, j])
  182. tx_i += 1
  183. logger.info("doing corr")
  184. correlator = Correlator(model)
  185. ncolumns = 4
  186. step = traces_x.shape[1] // ncolumns
  187. all_coefs = []
  188. for i in tqdm.trange(ncolumns):
  189. start = i * step
  190. end = (i + 1) * step
  191. coefs = correlator.corr_submatrix(traces_x[:, start:end])
  192. all_coefs.append(coefs)
  193. all_coefs = numpy.hstack(all_coefs)
  194. all_coefs = numpy.abs(all_coefs)
  195. max_by_key = numpy.max(all_coefs, axis=1)
  196. plt.plot(max_by_key)
  197. plt.show()
  198. def main(db):
  199. ntraces = 2000
  200. # traces = None
  201. # attack_firstorder_fft(db, traces, ntraces)
  202. # return
  203. traces = align(db, ntraces)
  204. # for i in range(10):
  205. # plt.plot(traces[i], color=numpy.hstack((numpy.random.random(3), [0.5])))
  206. # plt.show()
  207. attack_firstorder(db, traces, ntraces)
  208. attack_secondorder(db, traces, ntraces)
  209. if __name__ == "__main__":
  210. from tqdm.contrib.logging import logging_redirect_tqdm
  211. logging.basicConfig(level=logging.INFO)
  212. with logging_redirect_tqdm():
  213. db = h5py.File("./ASCAD_databases/ASCAD_desync100.h5", "r")
  214. main(db["Attack_traces"])