Skip to content

Commit

Permalink
test runs
Browse files Browse the repository at this point in the history
  • Loading branch information
ceesb committed Nov 18, 2017
1 parent 838cc97 commit b510f59
Show file tree
Hide file tree
Showing 23 changed files with 508 additions and 383 deletions.
12 changes: 7 additions & 5 deletions src/aes-gcm.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ function block_mul(X::UInt128, Y::UInt128)
return Z
end

function ghash(X::UInt128, Y::UInt128, H::UInt128)
return block_mul(xor(X,Y),H)
function ghash(X::UInt128, Y::UInt128, H::UInt128, leak::Function=(x,y)->y)
O = block_mul(xor(X,Y),H)
leak("ghash out", O)
return O
end

export GcmState
Expand Down Expand Up @@ -65,7 +67,7 @@ end

export setAuth

function setAuth(a::GcmState, Ab::Vector{UInt8})
function setAuth(a::GcmState, Ab::Vector{UInt8}, leak::Function=(x,y)->y)
abits = length(Ab) * 8
a.abits = abits
apad = 128 * div(abits + 127,128) - abits
Expand All @@ -79,11 +81,11 @@ function setAuth(a::GcmState, Ab::Vector{UInt8})
tail = 16 - apadbytes
tmp[1:tail] = Ab[end-tail+1:end]
X = hton(reinterpret(UInt128, tmp)[1])
a.S = ghash(X, a.S, a.H)
a.S = ghash(X, a.S, a.H, leak)
else
o = (b-1)*16
X = hton(reinterpret(UInt128, Ab[o+1:o+16])[1])
a.S = ghash(X, a.S, a.H)
a.S = ghash(X, a.S, a.H, leak)
end
end
end
Expand Down
8 changes: 5 additions & 3 deletions src/attackdes-core.jl
Original file line number Diff line number Diff line change
Expand Up @@ -330,11 +330,13 @@ function pick(scorecol::Vector{Float64}, col::Int, block::UInt8)
end

# a better way to get a round key from the scores
function getRoundKey(a::DpaAttack, params::DesAttack, phase::Int, sc::RankData)
if phase in [PHASE3;PHASE5]
function getPhaseKey(a::DpaAttack, params::DesAttack, phase::Int, sc::RankData)
if phase in [PHASE3;PHASE5]
targets = getTargets(sc, phase)
phaseOutput = a.phaseData
wrongdeskey = recoverKeyHelper(params, phase-1, phaseOutput[end-15:end-8], phaseOutput[end-7:end])
o1 = offset(a,phase-2)
o2 = offset(a,phase-1)
wrongdeskey = recoverKeyHelper(params, phase-1, phaseOutput[o1+1:o1+8], phaseOutput[o2+1:o2+8])

if params.direction == BACKWARD
encrypt = !params.encrypt
Expand Down
35 changes: 18 additions & 17 deletions src/conditional-bitwisereduction.jl
Original file line number Diff line number Diff line change
Expand Up @@ -19,29 +19,26 @@

export CondReduce

using ..Log

type CondReduce <: Cond
mask::Dict{Int,BitVector}
traceIdx::Dict{Int,Dict{Int,Int}}
globcounter::Int
worksplit::WorkSplit
trs::Trace
bitcompressedInitialized::Bool
logfile::SimpleCSV
usesamplescache::Bool
samplescache::Dict{Int,Dict{Int,BitVector}}
trs::Trace

function CondReduce(trs::Trace, logfile::Nullable{String}=Nullable{String}(), usesamplescache=true)
CondReduce(NoSplit(), trs, logfile, usesamplescache)
function CondReduce(trs::Trace, usesamplescache=true)
CondReduce(NoSplit(), trs, usesamplescache)
end

function CondReduce(worksplit::WorkSplit, trs::Trace, logfile::Nullable{String}=Nullable{String}(), usesamplescache=true)
function CondReduce(worksplit::WorkSplit, trs::Trace, usesamplescache=true)
mask = Dict{Int,BitVector}()
traceIdx = Dict{Int,Dict{Int,Int}}()
# @printf("Conditional bitwise sample reduction, split %s\n", worksplit)

new(mask, traceIdx, 0, worksplit, trs, false, SimpleCSV(logfile), usesamplescache, Dict{Int,Dict{Int,BitVector}}())
new(mask, traceIdx, 0, worksplit, false, usesamplescache, Dict{Int,Dict{Int,BitVector}}())
end
end

Expand All @@ -68,6 +65,7 @@ end
# only works on samples of BitVector type, do addSamplePass(trs, tobits)
# to create this input efficiently!
function add(c::CondReduce, trs::Trace, traceIdx::Int)
c.trs = trs
data::AbstractVector = getData(trs, traceIdx)
samples = Nullable{Vector{trs.sampleType}}()

Expand Down Expand Up @@ -121,11 +119,10 @@ function merge(this::CondReduce, other::CondReduce)
if this.traceIdx[idx][val] != other.traceIdx[idx][val]
cachedreftrace = getSamples(this.trs, other.traceIdx[idx][val])
cachedsamples = getSamples(this.trs, this.traceIdx[idx][val])

this.mask[idx][:] .&= .!(cachedreftrace .⊻ cachedsamples)
end
else
cachedsamples = getSamples(this.trs, other.traceIdx[idx][val])
# cachedsamples = getSamples(this.trs, other.traceIdx[idx][val])

this.traceIdx[idx][val] = other.traceIdx[idx][val]
end
Expand All @@ -136,6 +133,14 @@ end

function get(c::CondReduce)
@assert myid() == 1
if !isa(c.worksplit, NoSplit)
return @fetchfrom workers()[1] realget(Main.trs.postProcInstance)
else
return realget(c)
end
end

function realget(c::CondReduce)
if !isa(c.worksplit, NoSplit)
for worker in workers()
if worker == c.worksplit.worker
Expand All @@ -146,7 +151,7 @@ function get(c::CondReduce)
end
end
end

print("merged\n")
datas = Array[]
reducedsamples = Matrix[]

Expand Down Expand Up @@ -180,16 +185,13 @@ function get(c::CondReduce)
end

(keptnondups, keptnondupsandinvcols) = stats(bc)
Log.writecsvheader(c.logfile, "#traces","global dups", "global inv dups", map(x -> "cond sample red kb $x", 1:length(keys(c.mask)))...)
Log.writecsv(c.logfile, c.globcounter, keptnondups, keptnondupsandinvcols)

for k in sort(collect(keys(c.traceIdx)))
dataSnap = sort(collect(dataType, keys(c.traceIdx[k])))
idxes = find(c.mask[k] .& globalmask)
sampleSnap = BitArray{2}(length(dataSnap), length(idxes))
@printf("Reduction for %d: %d left after global dup col removal, %d left after removing the inv dup cols, %d left after sample reduction\n", k, keptnondups, keptnondupsandinvcols, length(idxes))
Log.writecsv(c.logfile, length(idxes))


for j in 1:length(dataSnap)
samples = getSamplesCached(c, k, dataSnap[j])
sampleSnap[j,:] = samples[idxes]
Expand All @@ -199,13 +201,12 @@ function get(c::CondReduce)
push!(reducedsamples, sampleSnap)
end

Log.writecsvnewline(c.logfile)

@printf("\nReduced %d input traces, %s data type\n", c.globcounter, string(dataType))

return (datas,reducedsamples)
end


function getGlobCounter(c::CondReduce)
return c.globcounter
end
Expand Down
28 changes: 25 additions & 3 deletions src/dpa.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,34 @@
#
# Authors: Cees-Bart Breunesse, Ilya Kizhvatov

export predict
type CPA <: NonIncrementalAnalysis
leakages::Vector{Leakage}

using ProgressMeter
function CPA()
return new([HW()])
end
end

show(io::IO, a::CPA) = print(io, "CPA")

getNrLeakageFunctions(a::CPA) = length(a.leakages)

maximization(a::CPA) = AbsoluteGlobalMaximization()

function computeScores(a::CPA, data::AbstractArray{In}, samples::AbstractArray, target::Target{In,Out}, kbvals::Vector{UInt8}) where {In,Out}
(tr,tc) = size(samples)
(dr,) = size(data)
tr == dr || throw(DimensionMismatch())

HL::Matrix{UInt8} = predict(data, target, kbvals, a.leakages)
C = cor(samples, HL)
return C
end

function printParameters(a::CPA)
@printf("leakages: %s\n", a.leakages)
end

# DPA prediction
function predict(data::AbstractArray{In,1}, t::Target{In,Out}, kcVals::Vector{UInt8}, leakages::Vector{Leakage}) where {In,Out}
(dr,) = size(data)
nrKcVals = length(kcVals)
Expand Down
25 changes: 24 additions & 1 deletion src/incremental-correlation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,25 @@
include("incremental-statistics.jl")

import ..Trs.add,..Trs.getGlobCounter
export IncrementalCorrelation,init,add,getGlobCounter
export IncrementalCorrelation

type IncrementalCPA <: IncrementalAnalysis
leakages::Vector{Leakage}

function IncrementalCPA()
return new([HW()])
end
end

show(io::IO, a::IncrementalCPA) = print(io, "Incremental CPA")

function printParameters(a::IncrementalCPA)
@printf("leakages: %s\n", a.leakages)
end

getNrLeakageFunctions(a::IncrementalCPA) = length(a.leakages)

maximization(a::IncrementalCPA) = AbsoluteGlobalMaximization()

type IncrementalCorrelation <: PostProcessor
worksplit::WorkSplit
Expand Down Expand Up @@ -34,6 +52,11 @@ show(io::IO, a::IncrementalCorrelation) = print(io, "Incremental correlation")
createTargetCache(t::Target{In,Out}) where {In,Out} = Vector{Out}(guesses(t))

function init(c::IncrementalCorrelation, targetOffsets::Vector{Int}, leakages::Vector{Leakage}, targets::Vector{Target})
if c.meanXinitialized
# FIXME quietly ignore
return
end

c.targetOffsets = targetOffsets
c.leakages = leakages
c.targets = targets
Expand Down
20 changes: 0 additions & 20 deletions src/incremental-statistics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -398,23 +398,3 @@ function getCorr(state::IncrementalCovarianceTiled)

return corr
end

function getRankData(state::IncrementalCovariance, reducer::Function)
scores = zeros(Float64, size(state.cov)[2])
offsets = zeros(Int, size(state.cov)[2])
corrCol = zeros(Float64, size(state.cov)[1])

xstddev = getStdDev(state.meanVarX)
ystddev = getStdDev(state.meanVarY)

for y in 1:size(corr)[2]
for x in 1:size(corr)[1]
corrCol[x] = 1/(state.n-1) * state.cov[x,y] / (xstddev[x] * ystddev[y])
end
(score,offset) = reducer(corColl)
scores[y] = score
offsets[y] = offset
end

return (scores,offsets)
end
45 changes: 44 additions & 1 deletion src/lra.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,28 @@
#
# Authors: Cees-Bart Breunesse, Ilya Kizhvatov

export lra
type LRA <: NonIncrementalAnalysis
basisModel::Function

function LRA()
return new(basisModelSingleBits)
end
end

show(io::IO, a::LRA) = print(io, "LRA")

function computeScores(a::LRA, data::AbstractArray{In}, samples::AbstractArray, target::Target{In,Out}, kbvals::Vector{UInt8}) where {In,Out}
C = lra(data, samples, target, a.basisModel, kbvals)
return C
end

function printParameters(a::LRA)
@printf("basismodel: %s\n", a.basisModel)
end

getNrLeakageFunctions(a::LRA) = 1

maximization(a::LRA) = GlobalMaximization()

# LRA for a single data column
function lra(data::AbstractArray{In}, samples::AbstractArray, t::Target{In,Out}, basisFunction::Function, keyChunkValues::Vector{UInt8}) where {In,Out}
Expand All @@ -24,3 +45,25 @@ function lra(data::AbstractArray{In}, samples::AbstractArray, t::Target{In,Out},
return R2
end

# some models for LRA

function basisModelSingleBits(x::Integer, bitWidth=8)
g = zeros(Float64, bitWidth+1)
for i in 1:bitWidth
g[i] = (x >> (i-1)) & 1
end
g[length(g)] = 1

return g
end

# TODO: understand why bitWidth=32 results in non-invertable matrices.
# function basisModelSingleBits(x::UInt32, bits=collect(1:31))
# g = zeros(Float64, length(bits)+1)
# for i in bits
# g[i] = (x >> (i-1)) & 1
# end
# g[length(g)] = 1

# return g
# end
37 changes: 32 additions & 5 deletions src/mia.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,36 @@
# MiaColumnData for the samples to be recomputed each time. Should be improved
# although the bulk of the work is in the p(x,y) computation

export mia
type MIA <: NonIncrementalAnalysis
leakages::Vector{Leakage}
sampleBuckets::Int

using ProgressMeter
function MIA()
return new([HW()], 9)
end
end

show(io::IO, a::MIA) = print(io, "MIA")

function printParameters(a::MIA)
@printf("leakages: %s\n", a.leakages)
@printf("#buckets: %d\n", a.sampleBuckets)
end

getNrLeakageFunctions(a::MIA) = length(a.leakages)

maximization(a::MIA) = GlobalMaximization()

function computeScores(a::MIA, data::AbstractArray{In}, samples::AbstractArray, target::Target{In,Out}, kbvals::Vector{UInt8}) where {In,Out}
(tr,tc) = size(samples)
(dr,) = size(data)
tr == dr || throw(DimensionMismatch())

# DPA prediction
HL::Matrix{UInt8} = predict(data, target, kbvals, a.leakages)
C = mia(samples, HL, a.sampleBuckets)
return C
end

type MiaColumnData{T}
uniques::Set{T}
Expand Down Expand Up @@ -119,17 +146,17 @@ function mia(O::AbstractArray, P::Matrix, nrOfObuckets=9)

# dump(Ocolumndata[1])

progress = Progress(co*cp,1)
# progress = Progress(co*cp,1)

for p in 1:cp
Pcolumndata = MiaColumnData{eltype(P)}(P[:,p])
for o in 1:co
C[o,p] = mia(Ocolumndata[o], Pcolumndata)
next!(progress)
# next!(progress)
end
end

finish!(progress)
# finish!(progress)

return C
end
Loading

0 comments on commit b510f59

Please sign in to comment.