-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject_code.tex
More file actions
3295 lines (2793 loc) · 113 KB
/
project_code.tex
File metadata and controls
3295 lines (2793 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\chapter{Codebase}
\section{FaucetEnv/namespaces.jl}
\begin{lstlisting}[language=JuliaLocal, style=julia]
FAUCET_PREFIX = "FaucetNS"
cmdify(s::String) = Cmd(String.(split(s, " ")))
function run_str(s::String)::Nothing
run(cmdify(s))
return nothing
end
function get_namespaces()::Vector{String}
return readlines(`ip netns ls`)
end
get_faucet_namespaces() = filter(x -> startswith(x, FAUCET_PREFIX), get_namespaces())
ns(name::String) = name == "" ? "" : "ip netns exec $FAUCET_PREFIX$name "
function create_namespace(name::String, netns::String="")::Nothing
run_str("ip netns add $FAUCET_PREFIX$name")
end
function delete_namespace(name::String)::Nothing
run_str("ip netns del $FAUCET_PREFIX$name")
end
function create_veth_pair(name1::String, name2::String, netns::String="")::Nothing
run_str("$(ns(netns))ip link add $FAUCET_PREFIX$name1 type veth peer name $FAUCET_PREFIX$name2")
end
create_veth_pair(name::String, netns::String="") = create_veth_pair("$(name)a", "$(name)b", netns)
function move_dev(name::String, dest_ns::String, source_ns::String="")::Nothing
run_str("$(ns(source_ns))ip link set $FAUCET_PREFIX$name netns $FAUCET_PREFIX$dest_ns")
end
function set_dev_address(dev::String, cidr::String, netns::String="")::Nothing
run_str("$(ns(netns))ip a add $cidr dev $FAUCET_PREFIX$dev")
end
function set_dev_up(dev::String, netns::String="")::Nothing
run_str("$(ns(netns))ip link set $FAUCET_PREFIX$dev up")
end
function create_bridge(name::String, netns::String="")::Nothing
run_str("$(ns(netns))ip link add $FAUCET_PREFIX$name type bridge")
end
function add_bridge_device(name::String, bridge::String, netns::String="")::Nothing
run_str("$(ns(netns))ip link set $FAUCET_PREFIX$name master $FAUCET_PREFIX$bridge")
end
get_devs(netns::String="")::String = read(cmdify("$(ns(netns))ip a"), String)
# +---------------------------+
# | ns: bridge |
# | |
# | br0 |
# | / \ |
# | sendb recvb |
# | |
# +---------------------------+
# +---------------------------+
# | ns: sender |
# | |
# | senda |
# | |
# +---------------------------+
# +---------------------------+
# | ns: receiver |
# | |
# | recva |
# | |
# +---------------------------+
# All have FAUCET_PREFIX prepended to them
NAMESPACES = ["bridge", "sender", "receiver", "aux"]
function create_Faucet_env()::Nothing
@info "Created namespaces." NAMESPACES
create_namespace.(NAMESPACES)
@info "Faucet namespaces" get_faucet_namespaces()
# Create sender veth pairs
create_veth_pair("senda", "sendb", "sender")
# Move senderb to bridge namespace
move_dev("sendb", "bridge", "sender")
set_dev_address("senda", "10.20.30.3/24", "sender")
# Create receiver veth pairs
create_veth_pair("recva", "recvb", "receiver")
# Move receiverb to bridge namespace
move_dev("recvb", "bridge", "receiver")
set_dev_address("recva", "10.20.30.2/24", "receiver")
# Create aux veth pairs
create_veth_pair("auxa", "auxb", "aux")
# Move auxb to receiver namespace
move_dev("auxb", "bridge", "aux")
set_dev_address("auxa", "10.20.30.201/24", "aux")
# Create bridge
create_bridge("br0", "bridge")
# Add senderb and receiverb to bridge
add_bridge_device("sendb", "br0", "bridge")
add_bridge_device("recvb", "br0", "bridge")
add_bridge_device("auxb", "br0", "bridge")
bridge_devs = get_devs("bridge")
sender_devs = get_devs("sender")
receiver_devs = get_devs("receiver")
# Bring devices up
set_dev_up("senda", "sender")
set_dev_up("sendb", "bridge")
set_dev_up("recva", "receiver")
set_dev_up("recvb", "bridge")
set_dev_up("auxa", "aux")
set_dev_up("auxb", "bridge")
set_dev_up("br0", "bridge")
@debug "Devs created and setup" bridge_devs sender_devs receiver_devs
return nothing
end
function teardown()::Nothing
@info "Deleting namespaces." NAMESPACES
delete_namespace.(NAMESPACES)
@info "Faucet namespaces" get_faucet_namespaces()
return nothing
end
\end{lstlisting}
\section{FaucetEnv/Test.jl}
\begin{lstlisting}[language=JuliaLocal, style=julia]
# sudo -E julia Test.jl
for i=1:256
run(`bash Test $i`)
end
\end{lstlisting}
\section{FaucetEnv/Traffic/rebase\_pcap.jl}
\begin{lstlisting}[language=JuliaLocal, style=julia]
# Take pcap file, and the address range to rebase.
# Args:
# 1 - Pcap file : String
# 2 - Address range to rebase : String
# 3 - New address range : String
# 4 - Excluded addresses : String (csv)
# Example:
# rebase_pcap.jl test.pcap 192.168.0.0 10.0.0.0 10.20.30.1,10.20.30.2
# !!! only does /24 ranges at the moment !!!
struct IpAddr
octet1::UInt8
octet2::UInt8
octet3::UInt8
octet4::UInt8
IpAddr(s::String) = new(parse.(UInt8, split(s, "."))...)
end
addr(o::Vector{UInt8}) = join(string.(Int64.(o)), ".")
function pcap_addr_stats(pcapf::String, range::Vector{UInt8})::Vector{UInt8} # Vector of endpoints
ref_dict = Dict{UInt8, Int64}()
# Read pcap as bytes
pcap = Vector{UInt8}()
open(pcapf, "r") do f
readbytes!(f, pcap, typemax(Int64))
end
println("Pcap length: $(length(pcap))")
# search for range in Pcap
for i in 1:length(pcap)-length(range)-1
if pcap[i:i+length(range)-1] == range
last_octet = pcap[i+length(range)]
if haskey(ref_dict, last_octet)
ref_dict[last_octet] += 1
else
ref_dict[last_octet] = 1
end
end
end
# Print stats
for (oct, count) ∈ ref_dict
println("Octet: $(addr(vcat(range, oct))), Count: $count")
end
return Vector{UInt8}([k for k ∈ keys(ref_dict)])
end
excluded_octects = parse.(UInt8, last.(split.(split(ARGS[4], ","), ".")))
println("Excluded octets: $excluded_octects")
pcapf = ARGS[1]
from = IpAddr(ARGS[2])
to = IpAddr(ARGS[3])
from_range = [from.octet1, from.octet2, from.octet3]
to_range = [to.octet1, to.octet2, to.octet3]
println("\n")
octs = pcap_addr_stats(pcapf, from_range)
remap = Dict{UInt8, UInt8}()
for o ∈ excluded_octects
while true
choice = rand(UInt8)
if choice ∉ octs && choice ∉ values(remap) && choice ∉ excluded_octects
remap[o] = choice
break
end
end
end
println("\n")
function rebase(pcapf::String, fromrange::Vector{UInt8}, torange::Vector{UInt8}, remap::Dict{UInt8, UInt8})::NTuple{2, String}
# Read pcap as bytes
pcap = Vector{UInt8}()
open(pcapf, "r") do f
readbytes!(f, pcap, typemax(Int64))
end
range_length = length(fromrange)
# search for range in Pcap
for i in 1:length(pcap)-range_length-1
if pcap[i:i+range_length-1] == fromrange
last_octet = pcap[i+range_length]
if last_octet ∈ excluded_octects
pcap[i+range_length] = remap[last_octet]
end
pcap[i:i+range_length-1] = torange
end
end
# Write new pcap
name = join(vcat("rebased", split.(pcapf, ".")[2:end]), ".")
rebased_name = "Dirty/" * name
open(rebased_name, "w") do f
write(f, pcap)
end
pcap_addr_stats(rebased_name, torange)
return (rebased_name, "Rebased/"*name)
end
(broken_checksum, fixed) = rebase(pcapf, from_range, to_range, remap)
run(Cmd(["python3", "fix_checksum.py", broken_checksum, fixed]))
\end{lstlisting}
\section{FaucetEnv/Faucet/test/t\_utils.jl}
\begin{lstlisting}[language=JuliaLocal, style=julia]
include("../src/utils.jl")
@testset "Utils" begin
@test IPv4Addr("192.168.0.1").host == 0xc0a80001
@test string(IPv4Addr("192.168.0.1")) == "192.168.0.1"
@test IPv4Addr([0xc0, 0xa8, 0x00, 0x01]).host == 0xc0a80001
end
\end{lstlisting}
\section{FaucetEnv/Faucet/test/runtests.jl}
\begin{lstlisting}[language=JuliaLocal, style=julia]
using Test
include("t_utils.jl")
@testset "Whole program" begin
# Setup
include("../src/main.jl")
using ..Inbound: init_receiver, listen
using ..CovertChannels: covert_methods
using .Outbound: init_environment, send_covert_payload
using .Environment: init_queue
# Init receiver queue first, so it doesn't miss anything
queue = init_receiver(:local)
# Then setup the sender
net_env = init_environment(target, init_queue())
covert_payload = Vector{UInt8}("Hello covert world!")
send_covert_payload(covert_payload, covert_methods, net_env)
# Then listen for the response
data = listen(queue, covert_methods)
@test data == covert_payload
end
\end{lstlisting}
\section{FaucetEnv/Faucet/docs/make.jl}
\begin{lstlisting}[language=JuliaLocal, style=julia]
using Documenter, DocumenterMarkdown
using Faucet
makedocs(
format = Documenter.HTML(),
sitename = "Faucet",
modules = [Faucet]
)
# Documenter can also automatically deploy documentation to gh-pages.
# See "Hosting Documentation" and deploydocs() in the Documenter manual
# for more information.
#=deploydocs(
repo = "<repository url>"
)=#
\end{lstlisting}
\section{FaucetEnv/Faucet/src/Faucet.jl}
\begin{lstlisting}[language=JuliaLocal, style=julia]
module Faucet
"""
WARNING!!
The module structure here is incorrect, and simply for the benefit of autodoc creation
"""
PADDING_METHOD=:covert
include("CircularChannel.jl")
include("constants.jl")
include("utils.jl")
module Environment
#import Layer_type, get_ip_from_dev, IPv4Addr, _to_bytes, CircularChannel
import ..Layer_type, ..CircularChannel, ..get_ip_from_dev, ..IPv4Addr, .._to_bytes, ..ENVIRONMENT_QUEUE_SIZE
export init_queue
include("environment/headers.jl")
include("environment/query.jl")
include("environment/bpf.jl")
include("environment/queue.jl")
include("environment/env_utils.jl")
end
module CovertChannels
import ..Layer_type, ..IPv4, ..Network_Type, ..TCP, ..Transport_Type, ..CircularChannel, ..MINIMUM_CHANNEL_SIZE
using ..Environment: Packet, get_tcp_server, get_queue_data, get_layer_stats, get_header, get_local_host_count
export covert_methods
include("covert_channels/covert_channels.jl")
include("covert_channels/microprotocols.jl")
end
module Outbound
struct Target end
target = Target()
import ..IPv4Addr, ..Network_Type, ..Transport_Type, ..Link_Type, ..Ethernet, ..IPv4, ..TCP, ..UDP, ..ARP, ..to_bytes, ..ip_address_regex, ..ip_route_regex, ..ip_neigh_regex, ..mac, ..to_net, .._to_bytes, ..integrity_check, ..PADDING_METHOD, ..remove_padding, ..CircularChannel
using ..CovertChannels: craft_change_method_payload, craft_discard_chunk_payload, craft_sentinel_payload, craft_recovery_payload, method_calculations, determine_method, covert_method, init, encode
using ..Environment: Packet, get_socket, sendto, await_arp_beacon, get_local_net_host, AF_PACKET, SOCK_RAW, ETH_P_ALL, IPPROTO_RAW
include("outbound/environment.jl")
include("outbound/packets.jl")
end
module Inbound
import ..MINIMUM_CHANNEL_SIZE, ..integrity_check, ..IPv4Addr, ..PADDING_METHOD, ..remove_padding, ..CircularChannel
using ..Environment: init_queue, local_bound_traffic, Packet, get_local_ip
using ..CovertChannels: SENTINEL, DISCARD_CHUNK, couldContainMethod, decode, covert_method, extract_method
using ..Outbound: ARP_Beacon
include("inbound/listen.jl")
end
end # module Faucet
\end{lstlisting}
\section{FaucetEnv/Faucet/src/CircularChannel.jl}
\begin{lstlisting}[language=JuliaLocal, style=julia]
# Define a "CircularChannel", a thread-safe channel, that will overwrite the oldest data when full
# Heavily inspired by:
# https://github.com/JuliaCollections/DataStructures.jl/blob/master/src/circular_buffer.jl
"""
CircularChannel{T}(sz::Int) where T
```
A thread-safe channel, that will overwrite the oldest data when full
Implements:
- put!(cc::CircularChannel{T}, data::T)
- take!(cc::CircularChannel{T})::T
- length(cc::CircularChannel{T})::Int
- size(cc::CircularChannel{T})::Tuple{Int}
- isempty(cc::CircularChannel{T})::Bool
- convert(::Vector{T}, cc::CircularChannel{T})::Vector{T}
```
"""
mutable struct CircularChannel{T} <: AbstractVector{T}
capacity::Int
@atomic first::Int
@atomic length::Int
buffer::Vector{T}
lock::Threads.Condition
function CircularChannel{T}(first::Int, len::Int, buf::Vector{T}) where {T}
first <= length(buf) && len <= length(buf) || error("Value of 'length' and 'first' must be in the buffers bounds")
return new{T}(length(buf), first, len, buf, Threads.Condition())
end
end
# Short hand
CircularChannel{T}(sz::Int) where T = CircularChannel{T}(1, 0, Vector{T}(undef, sz))
# Check bounds
Base.@propagate_inbounds function _buffer_index_checked(cc::CircularChannel, i::Int)
@boundscheck if i < 1 || i > cc.length
throw(BoundError(cc, i))
end
_buffer_index(cc, i)
end
# Implement the "circular" functionality
@inline function _buffer_index(cc::CircularChannel, i::Int)
n = cc.capacity
idx = cc.first + i - 1
return ifelse(idx > n, idx - n, idx)
end
# Get index and set index are only intended for internal use, only "supported" functions are put! and coverting to a vector
# Override getindex to use our circular functionality
@inline Base.@propagate_inbounds function Base.getindex(cc::CircularChannel, i::Int)
@lock cc.lock return cc.buffer[_buffer_index_checked(cc, i)]
end
# Override setindex to use our circular functionality
@inline Base.@propagate_inbounds function Base.setindex(cc::CircularChannel, data, i::Int)
@lock cc.lock cc.buffer[_buffer_index_checked(cc, i)] = data && return cc
end
@inline function Base.put!(cc::CircularChannel{T}, data) where T
lock(cc.lock)
try
data_converted = convert(T, data)
if cc.length == cc.capacity
@atomic cc.first = (cc.first == cc.capacity ? 1 : cc.first + 1)
else
@atomic cc.length += 1
end
@inbounds cc.buffer[_buffer_index(cc, cc.length)] = data_converted
notify(cc.lock)
return cc
finally
unlock(cc.lock)
end
end
@inline function Base.take!(cc::CircularChannel{T}) where T
lock(cc.lock)
try
if cc.length == 0
wait(cc.lock)
end
@atomic cc.length -= 1
return cc.buffer[_buffer_index(cc, cc.length + 1)]
finally
unlock(cc.lock)
end
end
# Define some generic functions
Base.length(cc::CircularChannel) = @atomic cc.length
Base.size(cc::CircularChannel) = (length(cc), )
Base.isempty(cc::CircularChannel) = length(cc) == 0
# Extract the data from the channel, in order
function Base.convert(::Vector{T}, cc::CircularChannel{T}) where T
lock(cc.lock)
try
first = cc.buffer[cc.first:cc.length]
second = cc.buffer[1:cc.first-1]
return Vector{T}[first; second]
finally
unlock(cc.lock)
end
end
\end{lstlisting}
\section{FaucetEnv/Faucet/src/constants.jl}
\begin{lstlisting}[language=JuliaLocal, style=julia]
#=
Define program constants
=#
# Program related constants
const ENVIRONMENT_QUEUE_SIZE = 150
const MINIMUM_CHANNEL_SIZE = 4
\end{lstlisting}
\section{FaucetEnv/Faucet/src/covert\_channels/microprotocols.jl}
\begin{lstlisting}[language=JuliaLocal, style=julia]
#=
Micro protcol definitions
*Protocols can be larger than the smallest channel*
- But must not rely on it
- Exception here is for recovering the channel, which is a special case
- DISCARD_CHUNK for example is padded with payload bits, but if there is not the capacity for it, then it isnt.
Protocols are passed through the covert channel,
the first channel used will be the most covert for the time being.
Main protocols:
first bit == 0b0 (MP_DATA)
=> Following bits are all data
first bit == 0b1 (MP_META)
=> Following bits are meta
Meta protocols:
Taking smallest as Y bits (including MP_META)
X = Y - 1 (Ignore the META flag)
X bits -> 2ˣ permutations
1 -> sentinel value
2ˣ- 1 -> DISCARD_CHUNK signal
2ˣ- 2 -> protocols
first X bits == "1" ^ X
=> Sentinel value (Start / end communication)
otherwise
=> index in covert_channels / DISCARD_CHUNK
=#
const SENTINEL = parse(UInt16, "1"^(MINIMUM_CHANNEL_SIZE), base=2)
const DISCARD_CHUNK = SENTINEL - 1
#=
Payload crafting functions
=#
"""
Take a unsigned integer (META_PROTOCOL) and pad it as required to fit a given capacity
"""
resize_payload(payload::Integer, capacity::Int)::String = resize_payload(UInt64(payload), capacity)
function resize_payload(payload::Unsigned, capacity::Int)::String
content = bitstring(payload)[end-MINIMUM_CHANNEL_SIZE+1:end] # Get the last 5 bits
padding = join([rand(("1","0")) for i ∈ 1:(capacity - length(content))])
return content * padding # Pad with random bits
end
"""
The DISCARD_CHUNK protocol is the meta_protocol,
but padded with the more payload bits
"""
function craft_discard_chunk_payload(capacity::Int, bits::String, pointer::Int64)::Tuple{Int64, String}
chunk = bitstring(DISCARD_CHUNK)[end-MINIMUM_CHANNEL_SIZE+1:end]
pointer_offset = capacity - length(chunk)
payload = chunk * bits[pointer:pointer+pointer_offset-1]
@assert length(payload) == capacity
@assert pointer_offset == length(payload) - length(chunk)
return pointer_offset, payload
end
"""
SENTINEL payload has no additional data just random padding
"""
craft_sentinel_payload(capacity::Int)::String = resize_payload(SENTINEL, capacity)
"""
Recovery payload has a specific format,
to prevent false positives:
```
| MINIMUM_CHANNEL_SIZE | UInt8 | 4 bits | ...
| verification_length | integrity ⊻ known_host | verification_length % 0x10 | padding
```
REQUIRES `method.capacity >= MINIMUM_CHANNEL_SIZE + 8 + 4`
"""
function craft_recovery_payload(capacity::Int, (verification_length, integrity)::Tuple{Int64, UInt8}, known_host::UInt8)::String
if capacity < MINIMUM_CHANNEL_SIZE + 8 + 4
@error "Capacity too small for recovery payload" capacity=capacity
return ""
end
meta = "1" ^ MINIMUM_CHANNEL_SIZE
meta *= bitstring(integrity ⊻ known_host)
payload = meta * bitstring(verification_length % 0x10)[end-3:end]
padding = join([rand(("1","0")) for i ∈ 1:(capacity - length(payload))])
@info "Recovery payload" vl=verification_length tl=verification_length % 0x10 meta payload
@assert length(payload) + length(padding) == capacity
return payload * padding
end
"""
payload structure:
```
| MINIMUM_CHANNEL_SIZE | UInt8 | ...
| Method_index | Offset | padding
```
If the capacity is too small, the offset is assumed to be 0.
This loses the benefit of the offset but allows usability in smaller channels.
"""
function craft_change_method_payload(method_index::Int, offset::UInt8, capacity::Int)::String
meta = "1" * bitstring(method_index)[end-MINIMUM_CHANNEL_SIZE+2:end]
meta *= bitstring(offset)
padding = join([rand(("1","0")) for i ∈ 1:(capacity - length(meta))])
payload = (meta * padding)[1:capacity]
midx, key = extract_method(payload)
@assert midx == method_index
@assert key == offset
return payload
end
"""
Remove the method index and offset from the method change payload.
"""
function extract_method(payload::String)::Tuple{Int, UInt8} # Method_index, key
key = parse(UInt8, lpad(payload[MINIMUM_CHANNEL_SIZE+1:min(MINIMUM_CHANNEL_SIZE+8, end)], 8, "0")[1:8], base=2)
method_index = parse(Int, payload[2:MINIMUM_CHANNEL_SIZE], base=2)
return method_index, key
end
#=
Micro protocol verification functions
=#
"""
channel_capacity_check(methods::Vector{covert_method})::Bool
Check that the channel sizes are large enough to fit the microprotocols
"""
function channel_capacity_check(methods::Vector{covert_method})::Bool
for method ∈ methods
if method.payload_size < MINIMUM_CHANNEL_SIZE
@error "Channel size too small for protocol" channel=method.name size=method.payload_size
return false
end
end
return true
end
"""
registered_channel_check(methods::Vector{covert_method})::Bool
Check that the number of channels is less than the sentinel value, and therefore can be addressed in our microprotocols
"""
function registered_channel_check(methods::Vector{covert_method})::Bool
if length(methods) >= SENTINEL - 1 # -1 for DISCARD_CHUNK
@error "Too many registered channels" channels=length(methods) max=SENTINEL-1
return false
end
return true
end
"""
channel_match_check(methods::Vector{covert_method})::Bool
Check that the channels in the target match the channels in the microprotocols
"""
function channel_match_check(methods::Vector{covert_method})::Bool
names = [method.name for method ∈ methods]::Vector{String}
if length(names) != length(target.channels)
@error "Channels in target and microprotocols do not match" target=target.channels microprotocols=names
return false
else
for i=1:lastindex(names)
if names[i] != target.channels[i]
@error "Channels in target and microprotocols do not match" target=target.channels microprotocols=names index=i
return false
end
end
end
return true
end
"""
Check that the microprotocols pass all the channel checks.
see also: [`channel_capacity_check`](@ref), [`registered_channel_check`](@ref), [`channel_match_check`](@ref).
"""
function check_channels(methods::Vector{covert_method})::Bool
return all([
channel_capacity_check(methods),
registered_channel_check(methods),
channel_match_check(methods)
])
end
\end{lstlisting}
\section{FaucetEnv/Faucet/src/covert\_channels/covert\_channels.jl}
\begin{lstlisting}[language=JuliaLocal, style=julia]
#=
Constant definitions
=#
const TCP_ACK = 0x0010
const TCP_SYN = 0x0002
const TCP_SYN_ACK = 0x0012
const TCP_PSH_ACK = 0x0018
#=
Covert channels
=#
struct covert_method{Symbol}
name::String # Readable name
layer::Layer_type # Layer it exists on
type::String # What packet type are we aiming for? (Packet will live at .layer)
covertness::Int8 # 1 - 10
payload_size::Int64 # bits / packet
covert_method(name::String, layer::Layer_type, type::String, covertness::Int64, payload_size::Int64)::covert_method{Symbol} = new{Symbol(name)}(name, layer, type, Int8(covertness), payload_size)
end
"""
Checks if a packet has the structure to contain a covert packet of the given type.
"""
function couldContainMethod(packet::Packet, m::covert_method)::Any
# Verify the packet could be a part of the covert channel
return split(string(typeof(get_header(packet, m.layer))), ".")[end] == m.type
end
#=
TCP_ACK_Bounce abuses the TCP handshake,
by spoofing the source to the destination and sending a request to a server,
the server responds with an ACK# of the original packets ISN+1,
the reciver can then ISN-1 and decode using a predefined technique
- Target IP (In env)
- Target Mac (in env)
- TCP Server Mac (or first gw mac)
- TCP Server IP
- TCP Server Port
=#
tcp_ack_bounce::covert_method{:TCP_ACK_Bounce} = covert_method(
"TCP_ACK_Bounce",
Layer_type(4), # transport
"TCP_header",
3,
32 # 4 bytes / packet
)
# Init function for TCP_ACK_Bounce
function init(::covert_method{:TCP_ACK_Bounce}, net_env::Dict{Symbol, Any})::Dict{Symbol, Any}
dest_mac, dest_ip, dport = get_tcp_server(net_env[:queue])
return Dict{Symbol, Any}(
:payload => Vector{UInt8}(),# ("Covert packet!"), # Obviously not a real payload
:env => net_env,
:network_type => IPv4::Network_Type,
:transport_type => TCP::Transport_Type,
:EtherKWargs => Dict{Symbol, Any}(
:dest_mac => dest_mac,
:source_mac => net_env[:src_mac]#net_env[:dest_first_hop_mac]
),
:NetworkKwargs => Dict{Symbol, Any}(
:source_ip => net_env[:dest_ip].host,
:dest_ip => dest_ip
),
:TransportKwargs => Dict{Symbol, Any}(
:flags => TCP_SYN::UInt16,
:dport => dport
)
)
end
# Encode function for TCP_ACK_Bounce
function encode(::covert_method{:TCP_ACK_Bounce}, payload::UInt32; template::Dict{Symbol, Any})::Dict{Symbol, Any}
template[:TransportKwargs][:seq] = payload - 0x1
return template
end
encode(m::covert_method{:TCP_ACK_Bounce}, payload::String; template::Dict{Symbol, Any})::Dict{Symbol, Any} = encode(m, parse(UInt32, payload, base=2); template=template)
# Decode function for TCP_ACK_Bounce
decode(::covert_method{:TCP_ACK_Bounce}, pkt::Packet)::UInt32 = pkt.payload.payload.payload.header.ack_num
#=
IPv4_identification utilises the 'random' identification header,
this can be replaced with encrypted (so essentially random) data.
=#
ipv4_identifaction::covert_method{:IPv4_Identification} = covert_method(
"IPv4_Identification",
Layer_type(3), # network
"IPv4_header",
8,
16, # 2 bytes / packet
)
# Init function for IPv4_Identification
function init(::covert_method{:IPv4_Identification}, net_env::Dict{Symbol, Any})::Dict{Symbol, Any}
target_mac, target_ip = net_env[:dest_first_hop_mac], net_env[:dest_ip].host
return Dict{Symbol, Any}(
:payload => Vector{UInt8}("Covert packet!"), # Obviously not a real payload
:env => net_env,
:network_type => IPv4::Network_Type,
:transport_type => TCP::Transport_Type,
:EtherKWargs => Dict{Symbol, Any}(
:dest_mac => target_mac,
),
:NetworkKwargs => Dict{Symbol, Any}(
:dest_ip => target_ip,
)
)
end
# Encode function for IPv4_Identification
function encode(::covert_method{:IPv4_Identification}, payload::UInt16; template::Dict{Symbol, Any})::Dict{Symbol, Any}
template[:NetworkKwargs][:identification] = payload
return template
end
encode(m::covert_method{:IPv4_Identification}, payload::String; template::Dict{Symbol, Any})::Dict{Symbol, Any} = encode(m, parse(UInt16, payload, base=2); template=template)
# Decode function for IPv4_Identification
decode(::covert_method{:IPv4_Identification}, pkt::Packet)::UInt16 = pkt.payload.payload.header.id
"""
Array of all covert methods, the order of these must be the same between sender & target
"""
covert_methods = Vector{covert_method}([
tcp_ack_bounce,
ipv4_identifaction,
])
"""
```markdown
Perform calculations for each covert_method based on the environment.
Note:
- Blacklisted methods are penalised (-90% score)
- Current method is encouraged (+10% score)
```
"""
function method_calculations(covert_methods::Vector{covert_method}, env::Dict{Symbol, Any}, Eₚ::Vector{Int64}=[], current_method::Int64=0)::NTuple{2, Vector{Float64}}
# Get the queue data
q = get_queue_data(env[:queue])
# Covert score, higher is better : Method i score = scores[i]
S = zeros(Float64, length(covert_methods))
# Rate at which to send covert packets : Method i rate = rates[i]
R = zeros(Float64, length(covert_methods))
if isempty(q)
@error "No packets in queue, cannot determine method" q
return S, R
end
#@warn "Hardcoded response to determine_method"
L = [get_layer_stats(q, Layer_type(i)) for i ∈ 2:4]
# Eₗ : Environment length : Number of packets in queue
Eₗ = length(q)
# Eᵣ : Environment rate : (Packets / second)
Eᵣ = Eₗ / abs(last(q).cap_header.timestamp - first(q).cap_header.timestamp)
# Eₛ : Environment desired secrecy : User supplied (Default: 5)
Eₛ = env[:desired_secrecy]
Eₕ = get_local_host_count(q, env[:dest_ip])
for (i, method) ∈ enumerate(covert_methods)
Lᵢ_temp = filter(x -> method.type ∈ keys(x), L)
if isempty(Lᵢ_temp)
@warn "No packets with valid headers" method.type L
continue
end
# Lᵢ : the layer that method i exists on
Lᵢ = Lᵢ_temp[1]
# Lₛ : The sum of packets that have a valid header in Lᵢ
Lₛ = +(collect(values(Lᵢ))...)
# Lₚ : Percentage of total traffic that this layer makes up
Lₚ = Lₛ / Eₗ
# Pᵢ is the percentage of traffic
Pᵢ = Lₚ * (Lᵢ[method.type] / Lₛ)
# Bᵢ is the bit capacity of method i
Bᵢ = method.payload_size
# Cᵢ is the penalty / bonus for the covertness
# has bounds [0, 2] -> 0% to 200% (± 100%)
Cᵢ = 1 - ((method.covertness - Eₛ) / 10)
# Score for method i
# Pᵢ * Bᵢ : Covert bits / Environment bits
# then weight by covertness
#@info "S[i]" Pᵢ Bᵢ Cᵢ Pᵢ * Bᵢ * Cᵢ
S[i] = Pᵢ * Bᵢ * Cᵢ
# Rate for method i
# Eᵣ * Pᵢ : Usable header packets / second
# If we used this much it would be +100% of the environment rate, so we scale it down
# by dividing by hosts on the network, Eₕ.
# then weight by covertness
# We don't want to go over the environment rate, so reshape covertness is between [0, 1] (1 being 100% of env rate)
# (Eᵣ * Pᵢ * (Cᵢ / 2)) / Eₕ : Rate of covert packets / second
# ∴ 1 / Eᵣ * Pᵢ * (Cᵢ / 2) : Interval between covert packets
#@info "R[i]" Eₕ Eᵣ Pᵢ Cᵢ/2 Eₕ / (Eᵣ * Pᵢ * (Cᵢ / 2))
R[i] = Eₕ / (Eᵣ * Pᵢ * (Cᵢ / 2))
end
# Eₚ (arg) : Environment penalty : Penalty for failing to work previously
for i ∈ Eₚ
S[i] *= 0.1 # 10% of original score
end
current_method != 0 && (S[current_method] *= 1.1) # Encourage current method (+10%)
return S, R
end
"""
Return the index of the method with the highest score, and the interval to send packets at.
The calculations are done in [`method_calculations`](@ref)
"""
function determine_method(covert_methods::Vector{covert_method}, env::Dict{Symbol, Any}, penalities::Vector{Int64}=[], current_method::Int64=0)::Tuple{Int64, Float64}
# Determine the best method to use
S, R = method_calculations(covert_methods, env, penalities, current_method)
# i : index of best method
# Sᵢ : score of best method
Sᵢ, i = findmax(S)
# Rᵢ : rate of best method
Rᵢ = R[i]
if allequal([S..., 0.0])
# If all scores are 0 then we have no valid methods, default to 1, with a large time interval
return 1, 100.0
end
# @debug "Determined covert method" covert_methods[i].name score=Sᵢ rate=Rᵢ
# Sort scores by second value in pair (score) and return highest
return i, Rᵢ
end
\end{lstlisting}
\section{FaucetEnv/Faucet/src/inbound/listen.jl}
\begin{lstlisting}[language=JuliaLocal, style=julia]
using AES
using Dates
import Base: -, >
# These functions are to remove bulky lines from the listen function
function -(a::Tuple{Float64, Int64}, b::Tuple{Float64, Int64})::Tuple{Float64, Int64}
# (a[1] - b[1], a[2] - b[2]) => a - b
return (a[1] - b[1], a[2] - b[2])
end
function >(a::Tuple{Float64, Int64}, b::Tuple{Float64, Int64})::NTuple{2, Bool}
# (a[1] > b[1], a[2] > b[2]) => a > b
return (a[1] > b[1], a[2] > b[2])
end
"""
dec(data::bitstring)::Vector{UInt8}
Decode a packet using Pre-shared key
& removing padding
"""
function dec(_data::String)::Vector{UInt8}
data = remove_padding(_data)
# Convert to bytes
bytes = Vector{UInt8}()
if length(data) % 8 != 0
@error "Data is not a multiple of 8, either recieved additional packets, or missing some"
error("Data length not a multiple of 8")
end
bytes = [parse(UInt8, data[i:i+7], base=2) for i ∈ 1:8:length(data)]