diff --git "a/pdf_data.json" "b/pdf_data.json" deleted file mode 100644--- "a/pdf_data.json" +++ /dev/null @@ -1,20 +0,0 @@ -[ - { - "tag": { - "category": "Runtime", - "subcategory": "Cloud Native Network", - "project_name": "Cilium", - "file_name": "CiliumFuzzingAudit2022.pdf" - }, - "content": "P R E S E N T S \nC i l i u m F u z z i n g A u d i t\nIn collaboration with the Cilium project maintainers and The Linux Foundation\nA u t h o r s\nAdam Korczynski <\nadam@adalogics.com\n>\nDavid Korczynski <\ndavid@adalogics.com\n>\nDate: 13th February, 2023\nThis report is licensed under Creative Commons 4.0 (CC BY 4.0)\n1\nCilium Fuzzing Audit, 2022\nCNCF security and fuzzing audits\nThis report details a fuzzing audit commissioned by the CNCF and the engagement is part\nof the broader e\ufb00orts carried out by CNCF in securing the so\u0000ware in the CNCF landscape.\nDemonstrating and ensuring the security of these so\u0000ware packages is vital for the CNCF\necosystem and the CNCF continues to use state of the art techniques to secure its projects\nas well as carrying out manual audits. Over the last handful of years, CNCF has been\ninvesting in security audits, fuzzing and so\u0000ware supply chain security that has helped\nproactively discover and fix hundreds of issues.\nFuzzing is a proven technique for finding security and reliability issues in so\u0000ware and the\ne\ufb00orts so far have enabled fuzzing integration into more than twenty CNCF projects\nthrough a series of dedicated fuzzing audits. In total, more than 350 bugs have been found\nthrough fuzzing of CNCF projects. The fuzzing e\ufb00orts of CNCF have focused on enabling\ncontinuous fuzzing of projects to ensure continued security analysis, which is done by way\nof the open source fuzzing project OSS-Fuzz\n1\n.\nCNCF continues work in this space and will further increase investment to improve\nsecurity across its projects and community. The focus for future work is integrating fuzzing\ninto more projects, enabling sustainable fuzzer maintenance, increasing maintainer\ninvolvement and enabling fuzzing to find more vulnerabilities in memory safe languages.\nMaintainers who are interested in getting fuzzing integrated into their projects or have\nquestions about fuzzing are encouraged to visit the dedicated cncf-fuzzing repository\nhttps://github.com/cncf/cncf-fuzzing\nwhere questions\nand queries are welcome.\n1\nhttps://github.com/google/oss-fuzz\n2Cilium Fuzzing Audit, 2022\nEx ecutive summary\nIn this engagement, Ada Logics worked on improving Ciliums fuzzing suite. At the time of this\nengagement, Cilium was already integrated into OSS-Fuzz, and the goal of this fuzzing audit was to\nbuild upon this integration and improve the fuzzing e\ufb00orts in a continuous manner.\nThe fuzzing audit added fuzzers for a lot of data processing APIs that found a number of di\ufb00erent\nissues in Cilium and its dependencies. None of the issues were considered critical, however, they\nrevealed some issues in Cilium that prompted rewrites and deprecation of some packages\nthroughout the source tree.\nPrior to this engagement, Ciliums OSS-Fuzz integration was set up in manner where the fuzzers\nand the OSS-Fuzz build script were located in Ciliums own repository\n2\n. In this fuzzing audit, most\ndevelopment of the fuzzers was carried out in the CNCF-Fuzzing repository,\nhttps://github.com/cncf/cncf-fuzzing/tree/main/projects/cilium\n.\nThis allowed the Ada Logics team\nto make smaller iterations of the fuzzers throughout the audit and avoid imposing the overhead of\nhaving the Cilium maintainers review trivial changes to the fuzzers. OSS-Fuzz was instructed to pull\nthe fuzzers from CNCF-Fuzzing in addition to the fuzzers from Ciliums repository.\nR e s u l t s s u m m a r i s e d\n14 fuzzers developed\nAll fuzzers added to Ciliums OSS-Fuzz integration\nAll fuzzers supported by Ciliums CIFuzz integration\n8 crashes were found.\n\u25cf\n5 cases of excessive memory allocation\n\u25cf\n1 index out of range\n\u25cf\n1 time out\n\u25cf\n1 nil-dereference\n2\nhttps://github.com/cilium/cilium/blob/master/test/fuzzing/oss-fuzz-build.sh\n3Cilium Fuzzing Audit, 2022\nT able of Contents\nCNCF security and fuzzing audits\n2\nExecutive summary\n3\nTable of Contents\n4\nCilium fuzzing\n5\nIssues found by fuzzers\n9\nRuntime stats\n19\nConclusions and future work\n20\n4Cilium Fuzzing Audit, 2022\nCilium fuzzing\nIn this section we present details on the Cilium fuzzing set up, and in particular the overall\nfuzzing architecture as well as the specific fuzzers developed.\nArchitecture\nA central component in the Cilium approach to fuzzing is continuous fuzzing by way of\nOSS-Fuzz. The Cilium source code and the source code for the Cilium fuzzers are the two\nkey so\u0000ware packages that OSS-Fuzz uses to fuzz Cilium. The following figure gives an\noverview of how OSS-Fuzz uses these two packages and what happens when an issue is\nfound/fixed.\nFigure 1.1: Ciliums fuzzing architecture\nThe current OSS-Fuzz set up builds the fuzzers by cloning the upstream Cilium Github\nrepository to get the latest Cilium source code and the CNCF-Fuzzing Github repository to\nget the latest set of fuzzers, and then builds the fuzzers against the cloned Cilium code. As\nsuch, the fuzzers are always run against the latest Cilium commit.\n5\nCilium Fuzzing Audit, 2022\nThis build cycle happens daily and OSS-Fuzz will verify if any existing bugs have been\nfixed. If OSS-fuzz finds that any bugs have been fixed OSS-Fuzz marks the crashes as fixed\nin the Monorail bug tracker and notifies maintainers.\nIn each fuzzing iteration, OSS-Fuzz uses its corpus accumulated from previous fuzz runs. If\nOSS-Fuzz detects any crashes when running the fuzzers, OSS-Fuzz performs the following\nactions:\n1.\nA detailed crash report is created.\n2.\nAn issue in the Monorail bug tracker is created.\n3.\nAn email is sent to maintainers with links to the report and relevant entry in the\nbug tracker.\nOSS-Fuzz has a 90 day disclosure policy, meaning that a bug becomes public in the bug\ntracker if it has not been fixed. The detailed report is never made public. The Cilium\nmaintainers will fix issues upstream, and OSS-Fuzz will pull the latest Cilium master\nbranch the next time it performs a fuzz run and verify that a given issue has been fixed.\nCilium Fuzzers\nIn this section we present a highlight of the Cilium fuzzers and which parts of Cilium they\ntest. In total, 14 fuzzers were written during the fuzzing audit.\nOverview\n#\nName\nPackage\n1FuzzLabelsfilterPkgcilium/pkg/labelsfilter\n2FuzzDecodeTraceNotifycilium/pkg/monitor\n3FuzzFormatEventcilium/pkg/monitor\n4FuzzPayloadEncodeDecodecilium/pkg/monitor/payload\n5FuzzElfOpencilium/pkg/elf\n6FuzzElfWritecilium/pkg/elf\n7FuzzMatchpatternValidatecilium/pkg/fqdn/matchpattern\n8FuzzMatchpatternValidateWithoutCachecilium/pkg/fqdn/matchpattern\n9FuzzParserDecodecilium/pkg/hubble/parser\n10FuzzLabelsParsecilium/pkg/k8s/slim/k8s/apis/labels\n11FuzzMultipleParserscilium/proxylib/cassandra\n12FuzzConfigParsecilium/pkg/bgp/config\n6Cilium Fuzzing Audit, 2022\n13FuzzNewVisibilityPolicycilium/pkg/policy\n14FuzzBpfcilium/pkg/bpf\nTarget APIs\n1: FuzzLabelsfilterPkg\nTests thatParseLabelPrefixCfg()\nandFilter()\nAPIs\nof thelabelsfilter\npackage.\n2: FuzzDecodeTraceNotify\nPasses an empty&TraceNotify{}\nand a pseudo-random\nbyte slice toDecodeTraceNotify()\n.\n3: FuzzFormatEvent\nCreates a pseudo-random&Payload{}\nand passes it to(m*MonitorFormatter).FormatEvent()\n.\n4: FuzzPayloadEncodeDecode\nDecodes aPayload{}\nwith a pseudo-random byte slice.\n5: FuzzElfOpen\nCreates a file with data provided by the fuzzer and opens it by way ofgithub.com/cilium/cilium/pkg/elf.Open()\n.\n6: FuzzElfWrite\nCreates a new Elf and writes pseudo-random data to it.\n7: FuzzMatchpatternValidate\nPasses a pseudo-random string togithub.com/cilium/cilium/pkg/fqdn/matchpattern.Validate()\n.\n8: FuzzMatchpatternValidateWithoutCache\nPasses a pseudo-random string togithub.com/cilium/cilium/pkg/fqdn/matchpattern.Validate()\n.\n9: FuzzParserDecode\nInstantiates a Hubble parser. It then creates aMonitorEvent\nand assigns either aPerfEvent\n,AgentEvent\nor aLostEvent\nto theMonitorEvent\u2019sPayload\n. Finally the\nfuzzer callsgithub.com/cilium/cilium/pkg/hubble/parser.(p*Parser).Decode()\n, passing theMonitorEvent\n.\n7Cilium Fuzzing Audit, 2022\n10: FuzzLabelsParse\nPasses a pseudo-random string togithub.com/cilium/cilium/pkg/k8s/slim/k8s/apis/labels.Parse()\n.\n11: FuzzMultipleParsers\nStarts a log server, inserts a pseudo-random policy text, creates a new proxylib connection\nand callsOnData()\nagainst the connection. When creating\nthe connection, the fuzzer\nchooses between the Cassandra, Kafka, R2d2 or Memcache parsers.\n12: FuzzConfigParse\nPasses the fuzzing testcase to thebgp\nconfiguration\nparser.\n13: FuzzNewVisibilityPolicy\nCreates aVisibilityPolicy\nusing the fuzz testcase\nas the annotation parameter.\n14: FuzzBpf\nCreates two files, a \u201cbp\ufb00File\u201d and an \u201celfFile\u201d. Pseudo-random data is written to each file.\nThe fuzzer then calls eitherStartBPFFSMigration()\norFinalizeBPFFSMigration()\n. If it callsFinalizeBPFFSMigration()\nit may set the\nrevert argument to true.\n8Cilium Fuzzing Audit, 2022\nIssues found by fuzzers\nA total of 8 unique crashes were reported during the audit. All crashes were triaged by the\nCilium team who tracked the issues internally. The issues are as follows:\n#\nTitle\nMitigation\n1\nCilium Monitor: Out of memory when decoding \nspecific payload data\nClose: WontFix\n2\nCilium Monitor: index out of range\nClose: WontFix\n3\nCilium Monitor: Out of memory panic\nClose: WontFix\n4\nExcessive processing time required for rules with \nlong DNS namesFuzzPayloadEncodeDecode\nImprove Cilium limits on \nmatchpattern\n5\nExcessive memory allocation when parsing MetalLB \nconfiguration\nDeprecate feature\n6\nExcessive memory usage when loading and writing \nELF file\nAvoid reading/writing ELFs \nas part of datapath load\n7\nExcessive memory consumption when reading bytes \nof bpf_elf_map\nAvoid reading/writing ELFs \nas part of datapath load\n8\nHubble: nil-dereference in three-four parser\nCheck if nil before reading\nIssue 1-3 were closed as WontFix\u02bces. These were true, reproducible crashes, but triaging\nshowed that they did not have impact on real-world use cases.\nPublic Github issues were created for issue 4, 5 and 6 to fix at a future date.\nIssue 7 and 8 were fixed in Cilium.\n9Cilium Fuzzing Audit, 2022\n1: Cilium Monitor: Out of memory when decoding specific\npayload data\nOSS-Fuzz bug tracker:\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=49119\nMitigation:\nClose: WontFix\nID:\nADA-CIL-FUZZ-1\nDescription\nA fuzzer found that a well-cra\u0000ed payload data byte slice could cause excessive memory\nconsumption of the host machine.\nOSS-Fuzz took the following steps to trigger the crash. Note that this happened inside the\nOSS-Fuzz environment which has a maximum of 2560Mb memory available:\n1234567891011packagepayload\nimport(\"testing\")\nfuncTestPoC(t *testing.T) {data := []byte{251,0,99,255,255,6}pl := &Payload{}pl.Decode(data)}\nFigure 1.1:Proof of concept payload to trigger issueADA-CIL-FUZZ-1\n\u2026 which resulted in allocating 3737Mb of memory that OSS-Fuzz reported as an\nout-of-memory issue:\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n==13== ERROR: libFuzzer: out-of-memory (used: 3336Mb; limit: 2560Mb) \nTo change the out-of-memory limit use -rss_limit_mb=\nLive Heap Allocations: 24124699 bytes in 32 chunks; quarantined: 44415 bytes in 46 chunks; 7488 other chunks; total \nchunks: 7566; showing top 95% (at most 8 unique contexts) \n24120888 byte(s) (99%) in 11 allocation(s) \n#0 0x52ef96 in __interceptor_malloc /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:69:3 \n#1 0x4ad997 in operator new(unsigned long) cxa_noexception.cpp \n#2 0x458342 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 \n#3 0x7f6e83556082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: \n1878e6b475720c7c51969e69ab2d276fae6d1dee)\nFigure 1.2: Stacktrace from running the test case against the Cilium code base.\nThe function where this issue may be triggered is run from the \"cilium monitor\" command,\nwhich may be invoked inside the Cilium container by a privileged user. Cilium exercises\ncontrol over the generation and processing of these messages, so the likelihood of\nmalformed input is low. The impacted component is not a long-running process so there is\nno expected availability or observability impact. As a consequence of this, the issue will be\nclosed without a fix.\n10Cilium Fuzzing Audit, 2022\n2: Cilium Monitor: index out of range\nOSS-Fuzz bug tracker:\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=49723\nMitigation:\nClose: WontFix\nID:\nADA-CIL-FUZZ-2\nDescription\nAn index out of range panic in Golangsgob\npackage\nwas triggerable from Ciliums payload\npackage when decoding aPayload\nwith a particularly\nwell-crafted testcase.\nProof of concept\nThe following test reproduces the issue. The key lines are 8 and 10, where line 8 contains\nthe payload and line 10 the entry point that causes the panic. The data produced on line 8\ncorresponds to the data generated by the fuzzer.\n123456789101112packagepayload\nimport(\"testing\")\nfuncTestPoC(t *testing.T) {data := []byte{18,127,255,2,0,248,127,255,255,255,255,255,255,255,255,255,25,67,36}pl := &Payload{}pl.Decode(data)}\nFigure 2.1:Proof of concept payload to trigger issueADA-CIL-FUZZ-2\nTo reproduce the issue the above test can be run against Cilium main branch commitb4794d690b5690d70c074bffd1db7593e3938e65\nby placing\nthe test inside thepkg/monitor/payload\ndirectory:\n1234git clone https://github.com/cilium/ciliumcd ciliumgit checkout b4794d690b5690d70c074bffd1db7593e3938e65cd pkg/monitor/payload\nFigure 2.2: Extracting the relevant commit of Cilium to reproduce ADA-CIL-FUZZ-2\nCreate the test aspoc_test.go\nwith the contents of\nthe test above and then rungo test-run=TestPoC\n. You should get the following stacktrace:\n11Cilium Fuzzing Audit, 2022\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\npanic: runtime error: index out of range [-9223372036854775808] [recovered] \npanic: runtime error: index out of range [-9223372036854775808] [recovered] \npanic: runtime error: index out of range [-9223372036854775808]\ngoroutine 19 [running]: \ntesting.tRunner.func1.2({0x653040, 0xc00015e048}) \n/usr/local/go/src/testing/testing.go:1396 +0x24e \ntesting.tRunner.func1() \n/usr/local/go/src/testing/testing.go:1399 +0x39f \npanic({0x653040, 0xc00015e048}) \n/usr/local/go/src/runtime/panic.go:884 +0x212 \nencoding/gob.catchError(0xc00016c1f0) \n/usr/local/go/src/encoding/gob/error.go:38 +0x6d \npanic({0x653040, 0xc00015e048}) \n/usr/local/go/src/runtime/panic.go:884 +0x212 \nencoding/gob.(*Decoder).decodeStruct(0xc00016c180?, 0xc00015c180, {0x655440?, 0xc0001ae0c0?, 0x4ec2ef?}) \n/usr/local/go/src/encoding/gob/decode.go:462 +0x2cc \nencoding/gob.(*Decoder).decodeValue(0xc00016c180, 0x485f0?, {0x62bc00?, 0xc0001ae0c0?, 0xc00016c198?}) \n/usr/local/go/src/encoding/gob/decode.go:1210 +0x24e \nencoding/gob.(*Decoder).recvType(0xc00016c180, 0x40) \n/usr/local/go/src/encoding/gob/decoder.go:67 +0x13c \nencoding/gob.(*Decoder).decodeTypeSequence(0xc00016c180, 0x0) \n/usr/local/go/src/encoding/gob/decoder.go:164 +0x7b \nencoding/gob.(*Decoder).DecodeValue(0xc00016c180, {0x644540?, 0xc000115230?, 0x8?}) \n/usr/local/go/src/encoding/gob/decoder.go:225 +0x18f \nencoding/gob.(*Decoder).Decode(0xc00016c180, {0x644540?, 0xc000115230?}) \n/usr/local/go/src/encoding/gob/decoder.go:202 +0x165 \ngithub.com/cilium/cilium/pkg/monitor/payload.(*Payload).DecodeBinary(...) \n/tmp/cilium/pkg/monitor/payload/monitor_payload.go:98 \ngithub.com/cilium/cilium/pkg/monitor/payload.(*Payload).ReadBinary(0x5007b4?, {0x6bc800?, 0xc000115260?}) \n/tmp/cilium/pkg/monitor/payload/monitor_payload.go:82 +0x3f \ngithub.com/cilium/cilium/pkg/monitor/payload.(*Payload).Decode(...) \n/tmp/cilium/pkg/monitor/payload/monitor_payload.go:65 \ngithub.com/cilium/cilium/pkg/monitor/payload.TestPOC(0x0?) \n/tmp/cilium/pkg/monitor/payload/pl_test.go:10 +0xad\nFigure 2.3: Stacktrace from running the test case against the Cilium code base.\nThis issue has been closed without a fix for the same reasons as ADA-CIL-FUZZ-1.\n12Cilium Fuzzing Audit, 2022\n3: Cilium Monitor: Out of memory panic\nOSS-Fuzz bug tracker\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=53070\nMitigation\nClose: WontFix\nID:\nADA-CIL-FUZZ-3\nDescription\nFuzzFormatEvent found a crash when a well-crafted Payload would be passed to(m*MonitorFormatter).FormatEvent()\n.\nThe vulnerable payload json was:{\"Data\":\"gvsB/yAgIA==\",\"CPU\":32,\"Lost\":32,\"Type\":9}\nOSS-Fuzz took the following steps to trigger the crash. Note that this happened inside the\nOSS-Fuzz environment which has a maximum of 2560Mb memory available:\n1234567891011121314151617packagemain\nimport(\"github.com/cilium/cilium/pkg/monitor/format\"\"github.com/cilium/cilium/pkg/monitor/payload\")\nfuncmain() {pl := &payload.Payload{Data: []byte(\"gvsB/yAgIA==\"),CPU:32,Lost:uint64(32),Type:9,}mf := format.NewMonitorFormatter(0,nil)mf.FormatEvent(pl)}\nFigure 3.0: Sample program that triggered the out-of-memory issue,inside the OSS-Fuzz environment\n\u2026 which resulted in allocating 3797Mb of memory that OSS-Fuzz reported as an\nout-of-memory issue:\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n==13== ERROR: libFuzzer: out-of-memory (used: 3797Mb; limit: 2560Mb) \nTo change the out-of-memory limit use -rss_limit_mb=\nLive Heap Allocations: 24131934 bytes in 41 chunks; quarantined: 142310 bytes in 56 chunks; 9911 other chunks; total \nchunks: 10008; showing top 95% (at most 8 unique contexts) \n24120824 byte(s) (99%) in 9 allocation(s) \n#0 0x52efb6 in __interceptor_malloc /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:69:3 \n#1 0x4ad9b7 in operator new(unsigned long) cxa_noexception.cpp \n#2 0x458362 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 \n#3 0x7f92b5028082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: \n1878e6b475720c7c51969e69ab2d276fae6d1dee)\nFigure 3.1: Stack trace reported by OSS-Fuzz\nThis issue has been closed without a fix for the same reasons as ADA-CIL-FUZZ-1 and\nADA-CIL-FUZZ-2.\n13Cilium Fuzzing Audit, 2022\n4: Excessive processing time required for rules with long DNS\nnames\nOSS-Fuzz bug tracker:\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=49019\nMitigation:\nImprove Cilium limits on matchpattern\nID:\nADA-CIL-FUZZ-4\nDescription\nA fuzzer found that a well-crafted payload passed togithub.com/cilium/cilium/pkg/fqdn/matchpattern.ValidateWithoutCache()\nwould\ncause Cilium to spend excessive time on a single process. The issue was reported by\nOSS-Fuzz as a time-out from spending 61 seconds on a single invocation ofValidateWithoutCache()\n.\nThe time-out happens when Cilium passes the testcase ontoregexp.Compile(TESTCASE)\n.\nCilium does this without checking the length of the input, and a long input string can make\nCilium spend excessive time on a single invocation. To trigger the crash, the fuzzer had\ngenerated a string longer than 70,000 bytes.\nThe issue was triaged by the Cilium team, and an issue has been opened here:\nhttps://github.com/cilium/cilium/issues/21491\nThe input t o this function is \ufb01rst submitted t o the K ubernetes apiser ver and st ored in a Cust om\nResour ce \ufb01eld. This r equir es a high le vel of privileges t o inser t. Furthermor e, Kubernetes typically\nimposes v arious limits on such \ufb01elds and on the siz e of the entir e resour ce objects, so it is\npossible that it is r ejected befor e it r eaches this point. K ubernetes will only then for ward the\nobject t o Cilium for Cilium t o then pr ocess this object with the code being fuzz ed in this scenario.\nDue t o these mitigating fact ors, the Cilium maintainers do not consider this t o be lik ely to occur\nin a r eal user envir onment. That said, impr ovements can be made in the Cilium tr ee which is why\nthe abo ve Github issue has been cr eated.\n14Cilium Fuzzing Audit, 2022\n5: Excessive memory allocation when parsing MetalLB\nconfiguration\nOSS-Fuzz bug tracker\n\u25cf\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=5\n1786\n\u25cf\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=5\n3059\nMitigation\nDeprecate feature\nID:\nADA-CIL-FUZZ-5\nDescription\nA fuzzer that tests the 3rd-party metallb config parser found that it is possible to cause\nexcessive memory consumption of the host machine if a well-crafted config file was being\nparsed.\nThe parsing routine failed at 2 different places, one in Cilium itself and one in the 3rd-party\nlibrary handling the parsing.\nThe found issues have prompted a discussion around deprecating MetalLB support instead\nof fixing the issue in the 3rd-party dependency itself:\nhttps://github.com/cilium/cilium/issues/22246\n15Cilium Fuzzing Audit, 2022\n6: Excessive memory usage when loading and writing ELF file\nOSS-Fuzz bug tracker:\n\u25cf\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=5\n1731\n\u25cf\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=5\n2981\n\u25cf\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=5\n3015\n\u25cf\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=5\n3066\nMitigation:\nAvoid reading/writing ELFs as part of datapath load\nID:\nADA-CIL-FUZZ-6\nDescription\nA fuzzer that Ciliums reading and writing routines of ELF files could trigger both an\nout-of-memory panics as well as a time-out from excessive processing time on a single elf\nfile. The root cause is an issue in Golang which is well known to the Golang maintainers. In\nGolang, it is not considered a security vulnerability issue in Golang itself due to the intended\nusage of theelf\npackage.\nTo trigger the issue, the fuzzer creates a file containing the test case. It then invokesgithub.com/cilium/cilium/pkg/elf.Open()\nwith the path\nto the created file.Open()\nreads the file and passes the file contents ontogithub.com/cilium/cilium/pkg/elf.NewELF()\nwhich passes\nthe file contents ontodebug/elf.NewFile()\nin the standard library where\nthe crash happens.\nCilium issue:\nhttps://github.com/cilium/cilium/issues/22245\nSignificant local privileges are required to invoke this bug, so this is not considered a security\nconcern by the Cilium core team. The Cilium maintainers have longer term plans to remove\nthis code, and this will be addressed as part of that effort.\n16Cilium Fuzzing Audit, 2022\n7: Excessive memory consumption when reading bytes of\nbpf_elf_map\nOSS-Fuzz bug tracker\n\u25cf\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=\n48961\nMitigation\nAvoid reading/writing ELFs as part of datapath load\nID:\nADA-CIL-FUZZ-7\nDescription\ngithub.com/cilium/cilium/pkg/bpf.parseExtra()\nparses\nextra bytes from the end of abpf_elf_map\nstruct. A fuzzer was able to invoke this\nmethod by callingStartBPFFSMigration\nandFinalizeBPFFSMigration\n.\nThe issue was fixed by removing theparseExtra()\napi\naltogether:\nhttps://github.com/cilium/cilium/pull/19159\n.\n17Cilium Fuzzing Audit, 2022\n8: Hubble: nil-dereference in three-four parser\nOSS-Fuzz bug tracker\n\u25cf\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=\n48960\n\u25cf\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=\n48957\nMitigation\nCheck if nil before reading\nID:\nADA-CIL-FUZZ-8\nDescription\nTwo nil-dereference panics were discovered in the Hubble three-four parser when accessing a field\nof(*Parser).linkGetter\n. At the time of occurrence,\nthe crash would not be triggerable\nthrough any existing code paths of Ciliums and was considered a cosmetic change. The fuzzer\ncreated the parser through Ciliums own constructor and passed\nnil\nfor all getters.\ncilium/pkg/monitor/datapath_debug.go\n254255\n256257caseDbgEncap:returnfmt.Sprintf(\"Encapsulating to node %d (%#x)from seclabel %d\",n.Arg1, n.Arg1, n.Arg2)caseDbgLxcFound:ifname := linkMonitor.Name(n.Arg1)\nFigure 8.1:Point of failure of ADA-CIL-Fuzz-8\ncilium/pkg/monitor/datapath_debug.go\n664665666667668669returnnil}\n// if the interface is not found, `name` will be an empty string and thus// omitted in the protobuf messagename, _ := p.linkGetter.GetIfNameCached(int(ifIndex))\nFigure 8.2:Point of failure of ADA-CIL-Fuzz-8\nFix:\nhttps://github.com/cilium/cilium/pull/20446\n18Cilium Fuzzing Audit, 2022\nRuntime stats\nContinuity is an important element in fuzzing because fuzzers incrementally build up a\ncorpus over time, therefore, the size of the corpus is a reflection of how much code the\nfuzzer has explored. OSS-Fuzz prioritises running fuzzers that continue to explore more\ncode, and the CPU time presented by OSS-Fuzz runtime stats is thus a reflection of how\nmuch work the fuzzers have performed. The following tables lists for each fuzzer\n3\nthe\namounts of tests executed as well as the total CPU hours devoted:\nName\nTotal times executed\nTotal runtime (hours)\nFuzzLabelsfilterPkg280,380,1081,332.7\nFuzzDecodeTraceNotify69,256,225,2594,816.5\nFuzzFormatEvent63,743,550129\nFuzzPayloadEncodeDecode1,689,825245.2\nFuzzElfOpen72,033,696224.2\nFuzzElfWrite28,824,726135\nFuzzMatchpatternValidate9,814,975,4565,146\nFuzzMatchpatternValidateWithoutCache1,250,359,4777,492\nFuzzParserDecode59,149,192,0956,927.5\nFuzzLabelsParse2,607,448,95513,693.5\nFuzzMultipleParsers74,5246.9\nFuzzConfigParse1,194,473,6236,805.3\nFuzzNewVisibilityPolicy8,817,227,3903,379.4\nFuzzBpf205,251,06912.8\n3\nAs per 6th December 2022.\n19Cilium Fuzzing Audit, 2022\nConclusions and future work\nThis fuzzing audit added 14 fuzzers to the Cilium projects. A total of 8 issues were found\nand at the time of this writing 5 of these issues have been fixed where 3 of the issues are\ndeclared WontFix. The fuzzers were added to Ciliums OSS-Fuzz integration, so that they\ncontinue to test Cilium for hard-to-find bugs as well as new code. OSS-Fuzz will\nperiodically pull the latest master of Cilium and run the fuzzers against that version of the\nsource tree.\nAs this fuzzing audit concludes, it is important to highlight that fuzzing is a continuous\ne\ufb00ort and that the fuzzers should continue to run through Ciliums OSS-Fuzz integration.\nSome bugs may take a long time to find, and to allow the fuzzers to get deep into the code\nbase, and it is imperative that the fuzzers keep running for that purpose.\nFor future work we recommend the following activities to the Cilium team:\nImprove Ciliums testability:\nIt may happen that some\nfuzzers find false positives that\ntheoretically are bugs but cannot be triggered in any execution path to the part of the code\nwhere the crash occurs. This was the case with issue #8 of this fuzzing audit that sparked a\ndiscussion about what to do in these cases for Cilium. An excellent point was made by\nCilium maintainer Joe Stringer who argued that false positives may be a sign that Cilium\nshould improve its testability:\nhttps://github.com/cilium/cilium/pull/20446#discussion_r919120926\n.\nThis is a great\nobservation that also highlights the importance of continuity in fuzzing; Some crashes\nrequired multiple development iterations of both fuzzers and the code base itself in order\nto fully utilize the capabilities of fuzzing, and continuously improving both sides is\nimportant.\nImprove coverage\n: We recommend making it a continuous\ne\ufb00ort to identify missing test\ncoverage of the fuzzers. This can be done using the code coverage visualisations provided\nby OSS-Fuzz.\nRequire fuzzers for new code:\nThe Cilium community\ndoes a good job in adding unit tests\nto new code contributions, and we recommend that Cilium makes a policy out of adding\nfuzzers in addition to unit tests. The overhead for writing fuzzers in addition to unit tests in\nGo is low, since Go has its own fuzzing engine that makes writing unit tests and fuzzers a\nsimilar experience:\nhttps://go.dev/security/fuzz/\n.\n20" - }, - { - "tag": { - "category": "Runtime", - "subcategory": "Cloud Native Network", - "project_name": "Cilium", - "file_name": "CiliumSecurityAudit2022.pdf" - }, - "content": "P R E S E N T S \nC i l i u m s e c u r i t y a u d i t\nIn collaboration with the Cilium maintainers, Open Source Technology Improvement Fund and The\nLinux Foundation\nA u t h o r s\nAdam Korczynski <\nadam@adalogics.com\n>\nDavid Korczynski <\ndavid@adalogics.com\n>\nDate: 13th February, 2023\nThis report is licensed under Creative Commons 4.0 (CC BY 4.0)\nCilium security audit, 2022\nT able of contents\nTable of contents\n2\nExecutive summary\n3\nProject Summary\n4\nAudit Scope\n4\nThreat model formalisation\n5\nFuzzing\n1\n2\nSupply chain\n1\n5\nIssues\n1\n8\n2Cilium security audit, 2022\nEx ecutive summary\nIn November and December 2022, Ada Logics carried out a security audit of Cilium on behalf of the\nCloud Native Computing Foundation and the Open Source Technology Improvement Fund. The\ngoal was to undertake a holistic security audit to draw on several security disciplines and evaluate\nand improve the security of Cilium.\nEngagement objectives\nThe audit had the following high-level objectives:\n1.\nThreat model formalisation\n: This part assessed the\ncritical components of Cilium along\nwith threat scenarios and architectural considerations relevant for Ciliums security posture.\n2.\nManual code audit\n: In this part, the auditing team\nmanually audited the Cilium code base.\n3.\nImprove OSS-Fuzz fuzzing suite\n: Cilium already had\na decent fuzz test suite in place, and\nin this part the auditing team assessed the test coverage for possible improvements.\n4.\nSLSA review\n: The audit team carried out a SLSA review\nto assess the compliance level of\nCilium.\nProcess\nAda Logics commenced the engagement with an initial assessment of the Cilium project evaluating\ndocumentation, source code, previous vulnerabilities, maintainer and community responses to\ncode issues and more. The purpose of this part was to get an initial understanding of how to\naddress the hands-on part of the audit.\nNext, Ada Logics dra\u0000ed the threat model and began the fuzzing as well as manual auditing\nprocess. The threat model evolved in parallel with the fuzzing and manual work. Fuzzers were\ncommitted upstream ad-hoc and added to Ciliums OSS-Fuzz integration. Security concerns\nidentified in the manual audit were shared with the Cilium team over two occasions: Once half-way\nthrough the audit and once at the end of the audit.\nFinally, Ada Logics dra\u0000ed the report detailing the overall engagement and shared this with the\nCilium team. Together, the teams refined the report for publication.\nResults and conclusions\nIn total 13 fuzzers were added to the test suite 3 of which were written for a critical 3rd-party\ndependency to Cilium. An OSS-Fuzz integration was also set up for this dependency. 22 security\nconcerns were identified during the manual auditing.\nThe overall conclusion is that Cilium is a well-secured project. The audit found no critical or high\nseverity vulnerabilities and found a lot of positives about the security of Cilium. This included both\nthe code displaying positive security awareness as well as the maintainers having thorough\nunderstanding about the security posture of Cilium.\n3Cilium security audit, 2022\nProject Summary\nThe auditors of Ada Logics were:\nName\nTitle\nEmail\nAdam Korczynski\nSecurity Engineer, Ada Logics\nAdam@adalogics.com\nDavid Korczynski\nSecurity Researcher, Ada Logics\nDavid@adalogics.com\nThe Cilium community members that were involved were:\nName\nTitle\nEmail\nJoe Stringer\nSo\u0000ware Engineer, Isovalent\njoe@isovalent.com\nLiz Rice\nChief Open Source O\ufb00icer, Isovalent\nliz@isovalent.com\nMathieu Payeur Levallois\nDirector of Engineering, Isovalent\nmpl@isovalent.com\nDavid Bimmler\nSo\u0000ware Engineer, Isovalent\ndavid.bimmler@isovalent.com\nMartynas Pumputis\nSo\u0000ware Engineer, Isovalent\nmartynas@isovalent.com\nNate Sweet\nSo\u0000ware Engineer, Isovalent\nnathan.sweet@isovalent.com\nAlexandre Perrin\nSo\u0000ware Engineer, Isovalent\nalex.perrin@isovalent.com\nMohit Marathe\nStudent, IIT (BHU)\nmohitmarathe23@gmail.com\nThe following facilitators of OSTIF were engaged in the audit:\nName\nTitle\nEmail\nDerek Zimmer\nExecutive Director, OSTIF\nDerek@ostif.org\nAmir Montazery\nManaging Director, OSTIF\nAmir@ostif.org\nAudit Scope\nThe following assets were in scope of the audit.\nCilium\nRepository\nhttps://github.com/cilium/cilium\nLanguage\nGo, C\n4Cilium security audit, 2022\nThreat model formalisation\nIn this section we outline the threat model of Cilium. We first outline the core components of\nCilium\u02bcs architecture. Next, we specify the threat actors that could have a harmful impact on a\nCilium deployment. Finally we exemplify several threat scenarios based on the observations made\nin the architecture overview and the specified threat actors.\nThe threat modelling has been conducted based on the following public resources:\n\u25cf\nCilium\u02bcs documentation including README files from Ciliums repository.\n\u25cf\nCilium\u02bcs source code at\nhttps://github.com/cilium/cilium\n.\n\u25cf\n3rd-party literature, documentation and media.\n\u25cf\nFeedback from Cilium maintainers\nThe intended audience for the threat model is the three target groups:\n1.\nSecurity researchers who wish to contribute to the security posture of Cilium.\n2.\nMaintainers of Cilium.\n3.\nUsers of Cilium.\nIt is expected that the threat model evolves over time based on both how Cilium and adoption\nevolves. As such, threat modelling should be seen as an ongoing e\ufb00ort. Future security disclosures\nto the Cilium security team are opportunities to evaluate the threat model of the a\ufb00ected\ncomponents and use cases of the reported disclosure.\n5Cilium security audit, 2022\nCilium architecture\nDaemon\nThe Cilium daemon runs on each node in the cluster and interacts with the container runtime and\nKubernetes via plugins to set up networking and security policies. At a high-level, it accepts\nconfiguration via Kubernetes or APIs that describe networking, service load-balancing, network\npolicies, and visibility & monitoring requirements.\nThe daemon listens for events from orchestration systems such as Kubernetes to learn when\ncontainers or workloads are started and stopped. It manages/creates the eBPF programs which the\nLinux kernel uses to control all network access in / out of those containers.\nSource files\n\u25cf\nhttps://github.com/cilium/cilium/tree/master/daemon\nPolicy repository\nThe policy repository has a list of policy rules that collectively make up a security policy. It is\ncreated by the Daemon when the core policy components are initialised. The Daemon is the only\ncomponent that interacts with the policy repository. Some actions performed by the Daemon\nagainst the policy repository are:\n\u25cf\nAdding new policy rules\n\u25cf\nDeleting policy rules\nCNI Plugin\n6\nCilium security audit, 2022\nCilium interacts with Kubernetes via Kubernetes\u02bc Container Network Interface. Kubernetes starts\nCiliums CNI Plugin when a pod gets scheduled or stopped on a node.\nMost logic of the CNI plugin is in its\nmain.go\n, where\nthe\nADD\n,\nCHECK\n,\nDEL\ncommands are\nimplemented.\nSource files:\n\u25cf\nhttps://github.com/cilium/cilium/tree/master/plugins/cilium-cni\neBPF Datapath\nOne of the central innovations in Cilium is the use of eBPF programs to observe and filter events in\nthe kernel. This is achieved by having eBPF programs attached to hook points, including within the\neXpress Data Path and in the tra\ufb00ic control subsystem. Specifically, the hooks applied by eBPF can\nbe summarised as follows:\n1.\nXDP\n: An early XDP BPF hook that is triggered at the\nearliest possible point in the network\ndriver. The program runs when a packet is received.\n2.\nTra\ufb00ic control (tc)\n: The next eBPF program is invoked\na few steps a\u0000er the networking\nstack has carried out initial processing of the packet. At this stage, Cilium has access to the\nsk_bu\ufb00 (socket bu\ufb00er).\n3.\nSocket hooks\n: When the packet reaches Layer 4, Cilium\nhas eBPF programs that attach to a\ncgroup and run on TCP events. \u201cThe socket send/recv hook runs on every send operation\nperformed by a TCP socket. At this point the hook can inspect the message and either drop\nthe message, send the message to the TCP layer, or redirect the message to another socket.\nCilium uses this to accelerate the datapath redirects as described below.\u201d\n1\nThe eBPF programs are run at the kernel level and, therefore, operate at a privileged level of the\nsystem where access could theoretically impact the integrity of the system. However, eBPF\nprograms are written in a subset of the C programming language that helps reduce the complexity\nof the programs, e.g. by disallowing unbounded loops to avoid deadlocks, and the impact of this is\nthat the programs become more simple to analyse. The subset of C does not itself guarantee\nmemory safety of the programs, however, to ensure further safety and guard against potential\nissues, the eBPF programs must be accepted by the eBPF verifier before being loaded into the\nkernel [\nhttps://docs.kernel.org/bpf/verifier.html\n].\n1\nhttps://docs.cilium.io/en/stable/concepts/ebpf/intro/#:~:text=The%20socket%20send,as%20described%20b \nelow\n.\n7Cilium security audit, 2022\nThreat actor enumeration\nIn this section we define the threat actors that we considered throughout the audit. These actors\nare defined pro-actively from studying the architecture of Cilium, and also by using a bottom-up\napproach based on findings in the Cilium code. Buttom-up in this context means when a coding\nissue is found we reason about what type of potential attacker can leverage such an issue.\nThreat actors is a classification of a person or group of people that could actively seek to negatively\nimpact Ciliums security posture and/or use flaws in Ciliums security posture to negatively impact\nusers of Cilium. In an attack scenario, a threat actor answers the question: \u201cWho would carry out\nthis attack?\u201d.\nActor\nDescription\nCilium contributor\nCilium is an open-source project that accepts contributions from the\ncommunity. Contributors can intentionally or unintentionally\ncommit vulnerable code to Cilium.\nCilium maintainer\nA person that maintains the public Cilium code repository and is \nconsidered a gatekeeper for additions to the project.\n3rd-party dependency \ncontributors\nCilium uses open-source dependencies, many of which accept \ncontributions from the community. A 3rd-party dependency \ncontributor is a person who contributes code to projects in Ciliums \ndependency tree.\n3rd-party dependency \nmaintainer\nA 3rd-party dependency maintainer is a person that manages public \ncode repositories that Cilium depends on.\nInternal user with limited \nprivileges\nAn actor that has access to a host that runs Cilium, but who has \nlower privileges than Cilium itself.\nInternal attacker\nAn actor that has escaped a container on a host running Cilium.\nExternal attacker\nExternal attacker on the internet.\nCilium administrators\nCilium administrators manage the Cilium clusters.\n8Cilium security audit, 2022\nThreat surface enumeration\nIn this section we iterate through the threat surface that we considered when auditing the code.\nThis was created iteratively as the audit progressed and the more we learned about the Cilium\ncodebase.\nPolicy enforcement bugs\nCilium\u02bcs policy model must be robust, secure and consistent. Users should be able to specify\npolicies that Cilium follows. Implementation errors in the policy enforcement code can lead to\nissues, e.g. policies are assumed to block something they do not block. In this context we are\nreferring to implementation issues in Cilium and not issues written in the policies themselves (for\nwhich there are suitable tools for learning and cra\u0000ing policies\nhttps://networkpolicy.io\n). Users\nshould be able to expect their policies to be enforced correctly by Cilium, however, implementation\nerrors may allow an attacker to circumvent an ill-enforced policy. There are two examples of this in\npast advisorised\nhttps://github.com/cilium/cilium/security/advisories/GHSA-wc5v-r48v-g4vh\nand\nhttps://github.com/cilium/cilium/security/advisories/GHSA-c66w-hq56-4q97\nIssues in the eBPF code\nThe eBPF programs of Cilium are susceptible to logical issues (note, we found no such issues in the\nactual auditing). This includes any filtering that they may promise from a logical perspective but do\nnot successfully enforce. For example, in the event the user specifies certain policies then these\npolicies must be accurately handled by the eBPF programs.\nThe Linux kernel eBPF verifier performs an exhaustive analysis of the eBPF programs, including\nanalysis of all possible execution paths, range analysis and more, which together ensure the safety\nof a given eBPF program. The verifier has been under thorough analysis, such as academic research\nfocusing on formal verification of its range analysis\n[\nhttps://sanjit-bhat.github.io/assets/pdf/ebpf-verifier-range-analysis22.pdf\n].\nThe consequence of\nthis is that the eBPF programs come with a high standard of security by default with respect to\nmemory corruption issues. For these reasons and due to timing constraints, in this audit we do not\ninspect the eBPF programs for possible memory corruption issues as problems in this context\nshould be caught by the verifier.\nIn general, the security of Cilium\u02bcs eBPF programs are dependent on the eBPF verifier as well as the\neBPF compiler toolchain. The verifier itself is complex and not limited to the same subset as eBPF\nprograms, and has previously had issues e.g. CVE-2020-8835. Therefore, limitations in the eBPF\nverifier or eBPF compiler toolchain can impact the integrity of the kernel when used with so\u0000ware\nsuch as Cilium.\nImportantly in this context is that\na\u0000er Cilium runs on the node, the node cannot run\nunprivileged eBPF programs because Cilium disables this ability for the rest of the kernel run time\n(using\nsysctl kernel.unprivileged_bpf_disabled=1)\n.\nThis is done in Cilium in order to prevent the\nclass of verifier vulnerabilities like CVE-2020-8835. This is also described here:\nhttps://docs.cilium.io/en/stable/bpf/#hardening\n.\nKvstore\n9Cilium security audit, 2022\nCilium can share data about cluster-wide state with all Cilium agents in two ways: in CRD\u02bcs or in a\nglobal key-value store. The two production-grade key-value stores supported are etcd and Consul,\nwith etcd being the most widely used. Cilium agents connect to the key-value store and obtain the\ndata in the kv-store to e\ufb00ectuate the desired state across pods:\nIf Cilium is deployed in kv-store mode, the Cilium etcd/Consul endpoints represent an attack\nsurface for the cluster which an attacker with local network access could attempt to exploit. If an\nattacker was able to compromise the kv-store instance to a degree where they could modify the\nentries of the store, they would de-facto have full control of the cluster.\nThis attack surface exists even if Cilium is not deployed in kv-store mode, in that Kubernetes per\ndefault uses etcd. As such, Cilium\u02bcs kv-store mode does not expose increased attack surface but\ndepends on Kubernetes\u02bc threat model for Cilium-specific configuration data.\nProper configuration by the Cilium user of the kv-store is critical in preventing exploitation of the\nadded attack surface from the kv-store.\nDepending on the configuration of the cluster, an attacker could utilize other properties of the\nkv-store deployment. If the kv-store runs in a container with root privileges, the attacker has a\nhigher chance of escalating to other nodes in the cluster.\nSupply-chain & runtime environment attacks\nCilium acts as a framework to route tra\ufb00ic through the Linux Kernel\u02bcs eBPF runtime in cloud-native\nuse cases. As such, the security of Kubernetes and the Linux Kernel a\ufb00ects Cilium users in several\nways. From one side, vulnerabilities in either Kubernetes or the Linux Kernel\u02bcs eBPF\nimplementation may bring Cilium users at risk despite the root cause not stemming from Cilium\nitself. From another side, Cilium may not interact with these 3rd-party ecosystems - like Kubernetes\nthe eBPF datapath - correctly which could lead to security issues.\nBesides large ecosystems like Kubernetes and the Linux kernel, Cilium also depends on 3rd-party\nlibraries for specific functionality in Cilium. A malicious attacker may find vulnerabilities in or\nintentionally commit vulnerable code to a 3rd-party dependency of Cilium. This could have an\ne\ufb00ect on Ciliums security posture. The attack surface through 3rd-party dependencies varies based\non the extent to which the dependencies are used. For example, the library\ngithub.com/vishvananda/netlink\nis widely used across\nthe entire cilium repository, whereas others\nare only used in tests.\n10\nCilium security audit, 2022\nAs an example, Cilium has previously been a\ufb00ected by vulnerabilities in Envoy which Cilium uses to\nenforce certain L7 policies. These are described in detail here:\n\u25cf\nhttps://github.com/cilium/cilium/security/advisories/GHSA-6hf9-972x-w\ufb003\n\u25cf\nhttps://github.com/cilium/cilium/security/advisories/GHSA-9hx8-3wfx-q2vw\nWe highlight here that the SLSA review given below outlines several of the practices that Cilium\ndeploys to protect against supply chain security attacks.\nComplex code assumptions regarding trusted input\nThroughout the audit we found several pieces of code that alone did not constitute a security\nvulnerability. However, the code had certain properties where minor changes in the code base\ncould result in security vulnerabilities without necessarily being obvious. Issue 4 and 5 are\nexamples of this, where unbounded memory allocation happens. At the given moment we did not\nfind these issues to be vulnerable, however, it is code that may be re-used improperly at a later\nstage can introduce a potential issue, where it may not be obvious that it is improperly re-used.\nIn essence, we consider this as an instance of complex code where assumptions of input to\nfunctions are not obvious. Consequently, it is not obvious from the code that it is indeed safe,\nwhere it could be made more obvious. A complex code base has security implications on the\nproject - albeit indirectly. Complex code conceals vulnerabilities which in turn makes them arduous\nto identify in merged code and during code reviews before the code is even merged. In addition,\ncomplex code increases the overhead of contributing to the project which in turn might lead to\nfewer security issues being uncovered by the community.\n11Cilium security audit, 2022\nFuzzing\nHaving high fuzz test coverage is an important element of the security measures of a project. At the\ncommencement of this audit, Cilium had carried out extensive work to integrate fuzzing in a\nprevious fuzzing audit also performed by Ada Logics. In this security audit, Ada Logics did an\nassessment of where the project could improve its fuzzing. The high-level tasks that we carried out\nwere:\nImprove test coverage of Cilium\nAda Logics wrote 10 fuzzers targeting policy handling as well as use of critical dependencies.\nAdd fuzzing to critical 3rd-party library\nAda Logics made an initial integration on OSS-Fuzz for the extensively usedgithub.com/vishvananda/netlink\ndependency. In addition\nwe wrote 3 fuzzers for APIs used\nby Cilium.github.com/vishvananda/netlink\nhas not\nbeen integrated into OSS-Fuzz at this\ntime due to lack of upstream response.\nCilium Fuzzers written during the audit\n#\nName\nPackage\n1FuzzCiliumNetworkPolicyParsepkg/k8s/apis/cilium.io/v2\n2FuzzCiliumClusterwideNetworkPolicyParsepkg/k8s/apis/cilium.io/v2\n3FuzzTestpkg/policy\n4FuzzRegenerateGatewayConfigspkg/egressgateway\n5FuzzParseCEGPpkg/egressgateway\n6FuzzGetLookupTablepkg/maglev\n7FuzzRoutespkg/testutils\n8FuzzListRulespkg/testutils\n9FuzzMapSelectorsToIPsLockedpkg/fqdn\n10FuzzNodeHandlerpkg/datapath/linux\nFuzzer descriptions\nFuzzCiliumNetworkPolicyParse\nParses a pseudo-randomized CiliumNetworkPolicy.\nFuzzCiliumClusterwideNetworkPolicyParse\n12Cilium security audit, 2022\nParses a pseudo-randomized CiliumClusterwideNetworkPolicy.\nFuzzTest\nCreates a pseudo-randomized api rule and calls its resolveEgressPolicy method.\nFuzzRegenerateGatewayConfigs\nCreates a Manager with pseudo-random nodes and policy configs and invokes the managers\nregenerateGatewayConfigs() method.\nFuzzParseCEGP\nParses a pseudo-randomized CiliumEgressGatewayPolicy.\nFuzzGetLookupTable\nPasses a pseudo-randomized map of backends to GetLookupTable().\nFuzzRoutes\nPasses a pseudo-randomized Route to multiple APIs in pkg/datapath/linux/route.\nFuzzListRules\nPasses a pseudo-randomized Rule to ListRules().\nFuzzMapSelectorsToIPsLocked\nPasses a pseudo-randomized map of FQDNSelectors to MapSelectorsToIPsLocked().\nFuzzNodeHandler\nCreates a linux node handler and a Node and passes the node to multiple methods of the linux\nnode handler.\nNetlink Fuzzers written during the audit\n#\nName\nPackage\n1FuzzLinkByNamenetlink\n2FuzzDeserializeRoutepkg/k8s/apis/cilium.io/v2\n3FuzzParseRawDatapkg/policy\nFuzzLinkByName\nPasses a pseudo-random string toLinkByName()\nwhich\nreturns aLink\n. Passes thatLink\ntoAddrList()\n.\nFuzzDeserializeRoute\nPasses raw data todeserializeRoute()\n.\n13Cilium security audit, 2022\nFuzzParseRawData\nPasses raw data toparseRawData()\n.\n14Cilium security audit, 2022\nSupply chain\nScorecard\nAt the time of this audit, Cilium has not integrated the Scorecard project.\nScorecard is an open source tool that helps projects assess security risks in their code base. It\nperforms a series of checks and scores the overall security posture on a scale from 1-10. If the\nproject scores low, Scorecard will provide recommendations for remediation and mitigation.\nCilium can use Scorecard for its own repository to increase transparency on the overall security\nposture of the project. This will help demonstrate what Cilium is doing right, and it will make it\nclear to the community which actionable issues require contributions. Integrating Scorecard into\nCilium would add the OpenSSF Scorecard badge to the README, where Cilium also has the\n\u201cOpenSSF best practices\u201d badge.\nThe Cilium community could consider requiring 3rd-party dependencies to integrate with\nScorecard to increase transparency of Cilium\u02bcs own supply chain. We recommend discussing this in\na public Github issue. In case this is something the community would like enforced, it too could be\na shared e\ufb00ort to bring Scorecard to Ciliums own supply chain.\nMore information on Scorecard can be found below:\n\u25cf\nhttps://securityscorecards.dev\n\u25cf\nhttps://github.com/ossf/scorecard\nSLSA review\nSLSA is a framework designed to mitigate threats against the so\u0000ware supply chain. Its\npurpose is to ensure integrity and prevent tampering of so\u0000ware artifacts. SLSA aims to\nensure the integrity of the source, the build and the availability of so\u0000ware artifacts\ntodefend against a series of known attack vectors of the so\u0000ware supply-chain\n2\n.\nOverall, Cilium is not yet SLSA 1 compliant, but with a few improvements can reach level 3.\nAda Logics follows the specification of SLSA v0.1 that is outlined here:\nhttps://slsa.dev/spec/v0.1/requirements\n. This version\nof the compliance requirements is\ncurrently in alpha and is likely to change.\nGiven the early stages of SLSA, projects looking to comply should consider compliance to\nbe an on-going process with regular assessment on whether all requirements are satisfied.\nEven when SLSA levels are met, Cilium should work actively on maintaining the achieved\n2\nhttps://slsa.dev/spec/v0.1/threats\n15Cilium security audit, 2022\nlevels, and we recommend that future security audits include an assessment on how\nCilium performs in maintaining the achieved SLSA compliance level. In this audit, several\nof the requirements were assessed by Cilium maintainers, and as a consequence of this\nintrospective work, we - Ada Logics - consider the Cilium project to be self-sustaining in\nprogressing with compliance. A Github issue has been created here for that purpose:\nhttps://github.com/cilium/cilium/issues/22740\n.\nCilium performs well in the Source and Build categories and meets most requirements in\nthese categories up to and including level 3.\nThe \u201cTwo-person viewed\u201d criteria under \u201cSource\u201d is fulfilled, since two Cilium maintainers\nare involved in merging pull requests. Not all pull requests are explicitly approved by the\nsecond maintainer, and we recommend that the second maintainer involved in a\npull-request review approves it before merging to avoid doubt of fulfilling this\nrequirement.\nThe primary missing domain for SLSA compliance is the provenance which is not\ngenerated during releases. The\nhttps://github.com/slsa-framework/slsa-github-generator\nproject o\ufb00ers a series of tools to generate SLSA level 3-compliant provenance attestation\nfor Github-hosted projects. These tools are created to specifically satisfy the\nprovenance-section of the three SLSA categories and will be a useful addition to Ciliums\nSLSA compliance. When Cilium makes the provenance available, it has achieved SLSA level\n1 compliance.\nSLSA compliance overview\nRequirement\nSLSA 1\nSLSA 2\nSLSA 3\nSLSA 4\nSource\n- Version controlled\n\u2713\n\u2713\n\u2713\nSource\n- Verified history\n\u2713\n\u2713\nSource\n- Retained indefinitely\n\u2713 (\n18 \nmo.)\n\u2713\nSource\n- Two-person reviewed\n\u2713\nBuild\n- Scripted build\n\u2713\n\u2713\n\u2713\n\u2713\nBuild\n- Build service\n\u2713\n\u2713\n\u2713\nBuild\n- Build as code\n\u2713\n\u2713\nBuild\n- Ephemeral environment\n\u2713\n\u2713\n16Cilium security audit, 2022\nBuild\n- Isolated\n\u2713\n\u2713\nBuild\n- Parameterless\n\u2713\nBuild\n- Hermetic\n\u26d4\nBuild\n- Reproducible\n\u26d4\nProvenance\n- Available\n\u26d4\n\u26d4\n\u26d4\n\u26d4\nProvenance\n- Authenticated\n\u26d4\n\u26d4\n\u26d4\nProvenance\n- Service generated\n\u26d4\n\u26d4\n\u26d4\nProvenance\n- Non-falsifiable\n\u26d4\n\u26d4\nProvenance\n- Dependencies complete\n\u26d4\nCommon\n- Security\nNot defined by SLSA requirements\nCommon\n- Access\n\u2713\nCommon\n- Superusers\n\u2713\n17Cilium security audit, 2022\nIssues\nThis section presents issues found during the audit. Find an up-to-date report on the status\nof these issues at https://github.com/cilium/cilium/issues/23121\n#\nTitle\nSeverity\n1\nOut of bounds file read in certificate manager\nGetSecrets()\nLow\n2\nMissing central documentation on using Cilium securely\nMedium\n3\nHandlers of the Cilium Docker plugin do not limit the size of the http request\nbody before decoding it.\nInformational\n4\nPossible memory exhaustion from CNI template rendering\nInformational\n5\nPossible excessive memory allocation\nLow\n6\nRace condition in Hubble Relay Peer Manager\nLow\n7\nRace condition in\npkg/policy.Repository.LocalEndpointIdentityRemoved()\nLow\n8\nDeprecated 3rd-party library\nInformational\n9\nTOCTOU race condition in endpoint file move helper function\nLow\n10\nRedundant return statements\nInformational\n11\nRedundant imports\nInformational\n12\nRedundant function parameters\nInformational\n13\nTOCTOU race condition in sockops\nbp\u0000oolLoad\nLow\n14\nLevel of trust for input from cloud providers is too high\nLow\n15\nBGP configuration file is read entirely into memory\nLow\n16\nRace condition when starting operator apiserver\nLow\n17\nBad code practice: Identical identifier of import and variable\nLow\n18\nDeadlock from locked mutex\nMedium\n19\nPossible type confusions\nLow\n20\nIll-defined contexts\nInformational\n21\nUse of deprecated TLS version\nInformational\n22\nDeprecated function calls\nLow\n18Cilium security audit, 2022\n1: Out of bounds file read in certificate managerGetSecrets()\nOverall severity:\nLow\nID:\nADA-CIL-1\nLocation:\nhttps://github.com/cilium/cilium/blob/e4af2f9a0c28c84090c7142e241 \nc2749a3f84ed9/pkg/crypto/certificatemanager/certificate_manager.go \n#L42\nCWE:\n\u25cf\nCWE-125: Out-of-bounds Read\nDescription\nAn attacker that can create a symlink in thecertPath\nof a given namespace can potentially read\nfiles outside of thecertPath\n.\nhttps://github.com/cilium/cilium/blob/314ca7baef f4f568f fc0bad95124e40665b1f88c/pkg/crypto/certificatemanager/ \ncertificate_manager .go#L42\nfunc(m *Manager)GetSecrets(ctx context.Context,secret *api.Secret, nsstring) (string,map[string][]byte, error) {...nsName := filepath.Join(ns, secret.Name)...certPath := filepath.Join(m.rootPath, nsName)files, ioErr := os.ReadDir(certPath)ifioErr ==nil{secrets :=make(map[string][]byte,len(files))for_, file :=rangefiles {varbytes []byte\npath := filepath.Join(certPath, file.Name())bytes, ioErr = os.ReadFile(path)ifioErr ==nil{secrets[file.Name()] = bytes}}\niflen(secrets) ==0&& ioErr !=nil{returnnsName,nil, ioErr}returnnsName, secrets,nil}secrets, err := m.k8sClient.GetSecrets(ctx, ns, secret.Name)returnnsName, secrets, err}\nThe root cause of the issue is thatos.ReadFile()\nresolves symlinks. For example, an attacker\ncould create a symlink in certPath with the filename \u201ctls.key\u201d linking to a cert file elsewhere on the\nmachine. m.GetSecrets would then first read all the files in certPath:\nfiles, ioErr := os.ReadDir(certPath)\n19Cilium security audit, 2022\nCilium then proceeds to read filenames. Here,path\nwould be correct, but Cilium would resolve a\nsymlink. bytes could be the file contents of the file being linked to in a symlink.\npath := filepath.Join(certPath, file.Name())bytes, ioErr = os.ReadFile(path)\nThe file contents are stored by filename:\nsecrets[file.Name()] = bytes\nNote that there is also a TOCTOU race condition in this part of the code.GetSecrets()\nonly uses\nthe file names in the directory and subsequently reads the files on their path, the files could\ntheoretically be changed in the time between the invocation ofos.ReadDir()\nandos.ReadFile()\n.\nThe \u02bbcertPath\u02bc is considered a privileged directory created by the privileged user. Thus, there is no\nescalation of privileges since the privileged user will also have access to the linked files in a\nsymlink.\u201d\n20Cilium security audit, 2022\n2: Missing central documentation on using Cilium securely\nOverall severity:\nMedium\nID:\nADA-CIL-2\nLocation:\nDocumentation\nFix:\nhttps://github.com/cilium/cilium/pull/23599\nDescription\nMisconfiguration is a major security problem with misconfiguration currently ranking 5 on OWASP\u02bcs\ntop ten (2021). In cloud environments data indicates misconfiguration is the most significant\nreason for unnecessary security risk exposure\n3\n. Cilium\nusers should be able to confidently follow\nindustry standards in their deployments, and the documentation should provide this information.\nCilium should also list whether there are limitations of the default setting from a security\nperspective.\nCilium's documentation is extensive and provides information on both internals, the fundamentals\nof eBPF as well as usage and getting started. The documentation also includes walk-throughs of\nusing various common components that might be used in an application deployment alongside\nCilium:\n\u25cf\nHow to secure gRPC:\nhttps://docs.cilium.io/en/v1.12/gettingstarted/grpc/\n\u25cf\nGetting Started Securing Elasticsearch:\nhttps://docs.cilium.io/en/v1.12/gettingstarted/elasticsearch/\n\u25cf\nHow to Secure a Cassandra Database:\nhttps://docs.cilium.io/en/v1.12/gettingstarted/cassandra/\n\u25cf\nGetting Started Securing Memcached:\nhttps://docs.cilium.io/en/v1.12/gettingstarted/memcached/\nThese are great tutorials to include in the documentation, however, users are required to read\nthrough the entire documentation to extract all security-relevant information on configuration.\nThis is a time-consuming task, magnified by some tutorials being in a step-by-step format requiring\nsetting up a test environment. The consequences of this may be that some CIlium users postpone\nextracting all documentation relevant to securely configuring Cilium, or that some users go\nthrough the documentation but fail to absorb all security-relevant information because it is\nscattered across the entire documentation.\nWe recommend creating a single-page piece of documentation that in short-form covers all known\nconfiguration points that could put users at risk if misconfigured. This will ensure that adopters can\nquickly and confidently go through all best-practice configurations and ensure they follow the\nrecommended standards.\nFor examples of security best practice documentation, see:\n3\nhttps://www.armosec.io/blog/what-we-learned-from-scanning-over-10k-kubernetes-clusters/\n21Cilium security audit, 2022\n\u25cf\nhttps://istio.io/latest/docs/ops/best-practices/security/\n\u25cf\nhttps://github.com/kubeedge/community/blob/master/sig-security/sig-security-audit/Kub\neEdge-threat-model-and-security-protection-analysis.md\n22Cilium security audit, 2022\n3. Handlers of the Cilium Docker plugin do not limit the size of\nthe http request body before decoding it\nOverall severity:\nLow\nID:\nADA-CIL-3\nLocation:\nhttps://github.com/cilium/cilium/blob/a5901e562faae14b86fc02d6ed1954641\n34e9586/plugins/cilium-docker/driver/driver.go\nCWE:\n\u25cf\nCWE-400: Uncontrolled Resource Consumption\nDescription\nThe Cilium Docker plugin does not check the size of the request body before decoding it. An http\nrequest with a large body could cause temporary DoS of the machine. Local testing demonstrated a\ndenial of the machine of ~ 10 seconds before Go terminated.\nThe issue exists here:\nhttps://github.com/cilium/cilium/blob/a5901e562faae14b86fc02d6ed195464134e9586/plugins/cilium-docke\nr/driver/driver.go#L327\nfunc(driver *driver)createNetwork(w http.ResponseWriter,r *http.Request) {varcreate api.CreateNetworkRequesterr := json.NewDecoder(r.Body).Decode(&create)iferr !=nil{sendError(w,\"Unable to decode JSON payload: \"+err.Error(),http.StatusBadRequest)return}log.WithField(logfields.Request, logfields.Repr(&create)).Debug(\"NetworkCreate Called\")emptyResponse(w)}\nAs well as these places:\n\u25cf\nhttps://github.com/cilium/cilium/blob/a5901e562faae14b86fc02d6ed195464134e9586/plugins/ciliu\nm-docker/driver/driver.go#L340\n\u25cf\nhttps://github.com/cilium/cilium/blob/a5901e562faae14b86fc02d6ed195464134e9586/plugins/ciliu\nm-docker/driver/driver.go#L360\n\u25cf\nhttps://github.com/cilium/cilium/blob/a5901e562faae14b86fc02d6ed195464134e9586/plugins/ciliu\nm-docker/driver/driver.go#L436\n\u25cf\nhttps://github.com/cilium/cilium/blob/a5901e562faae14b86fc02d6ed195464134e9586/plugins/ciliu\nm-docker/driver/driver.go#L456\n\u25cf\nhttps://github.com/cilium/cilium/blob/a5901e562faae14b86fc02d6ed195464134e9586/plugins/ciliu\nm-docker/driver/driver.go#L474\n\u25cf\nhttps://github.com/cilium/cilium/blob/a5901e562faae14b86fc02d6ed195464134e9586/plugins/ciliu\nm-docker/driver/driver.go#L513\n23Cilium security audit, 2022\n\u25cf\nhttps://github.com/cilium/cilium/blob/a5901e562faae14b86fc02d6ed195464134e9586/plugins/ciliu\nm-docker/driver/ipam.go#L68\n\u25cf\nhttps://github.com/cilium/cilium/blob/a5901e562faae14b86fc02d6ed195464134e9586/plugins/ciliu\nm-docker/driver/ipam.go#L81\n\u25cf\nhttps://github.com/cilium/cilium/blob/a5901e562faae14b86fc02d6ed195464134e9586/plugins/ciliu\nm-docker/driver/ipam.go#L93\n\u25cf\nhttps://github.com/cilium/cilium/blob/a5901e562faae14b86fc02d6ed195464134e9586/plugins/ciliu\nm-docker/driver/ipam.go#L142\nThis binary is not distributed or installed in Cilium environments. It's used for development\npurposes in some of the older testing infrastructure and we've been discussing getting rid of it.\n24Cilium security audit, 2022\n4. Possible memory exhaustion from CNI template rendering\nOverall severity:\nInformational\nID:\nADA-CIL-4\nLocation:\nhttps://github.com/cilium/cilium/blob/12b7b11e10c87dce2704d4252d22\ufb00202a48ebc1\n/daemon/cmd/cni.go#L271\nCWE:\n\u25cf\nCWE-400: Uncontrolled Resource Consumption\nDescription\nCiliums CNI injection mechanism contains several memory allocations with no upper bounds that\nmay end in a memory exhaustion vulnerability. We did not find a way for this to be vulnerable at\nthe moment, however, we highlight this as a possible issue in that it may be exposed in the future.\nThe root cause of the issue is that Cilium merges two byte slices without enforcing an upper limit\non either. There are several places where this could fail, and we list these further below. First we\npresent the dataflow of the CNI injection. The two byte slices being merged are:\n1.\nA CNI template containing an aws CNI entry. This is the entry that gets added to the CNI\nconfiguration file.\n2.\nThe contents of the CNI configuration file.\nThe merging happens inrenderCNIConf()\n:\nfuncrenderCNIConf(opts *option.DaemonConfig, confDirstring) (cniConfig []byte, errerror) {\nifopts.CNIChainingMode ==\"aws-cni\"{pluginConfig := renderCNITemplate(awsCNIEntry, opts)cniConfig, err = mergeExistingAWSCNIConfig(confDir, pluginConfig)iferr !=nil{returnnil, err}}else{...}\n...returncniConfig,nil}\nrenderCNIConf\ncreates the bytes that will later be\nadded to the existing CNI configuration\nfile. This happens inrenderCNITemplate\n:\nfuncrenderCNITemplate(instring, opts *option.DaemonConfig)[]byte{data :=struct{DebugboolLogFilestring\n25Cilium security audit, 2022\n}{Debug: opts.Debug,LogFile: opts.CNILogFile,}\nt := template.Must(template.New(\"cni\").Parse(in))\nout := bytes.Buffer{}iferr := t.Execute(&out, data); err !=nil{panic(err)// impossible}returnout.Bytes()}\nrenderCNITemplate\nadds the values of theDebug\nandCNILogFile\nfields from theDaemonConfig\nto theawsCNIEntry\ntemplate:\nconstawsCNIEntry =`{\"type\": \"cilium-cni\",\"enable-debug\": {{.Debug | js }},\"log-file\": \"{{.LogFile | js }}\"}`\nThis template is then passed tomergeExistingAWSCNFConfig\nwhich reads the existing cni\nconfig file and adds the Cilium plugin:\nfuncmergeExistingAWSCNIConfig(confDirstring, pluginConfig[]byte) ([]byte, error) {awsFiles := []string{\"10-aws.conflist\",\"10-aws.conflist.cilium_bak\"}found, err := findFile(confDir, awsFiles)iferr !=nil{returnnil, fmt.Errorf(\"could not find existingAWS CNI config forchaining %w\", err)}\ncontents, err := os.ReadFile(found)iferr !=nil{returnnil, fmt.Errorf(\"failed to read existingAWS CNI config %s: %w\",found, err)}\n// We found the CNI configuration,// inject Cilium as the last chained pluginout, err := sjson.SetRawBytes(contents,\"plugins.-1\",pluginConfig)iferr !=nil{returnnil, fmt.Errorf(\"failed to modify existingAWS CNI config at %s:%w\", found, err)}log.Infof(\"Inserting cilium in to CNI configurationfile at %s\", found)returnout,nil}\n26Cilium security audit, 2022\nFinally the merged aws plugin and the existing file contents are written back to the CNI config file.\nSince there are no upper bounds on the size of the template or the size of the existing CNI\nconfiguration file, Cilium may try to allocate excessive memory in the CNI merging workflow. At the\nmoment, we have found 2 ways to manipulate the amount of allocated memory:\n1.\nCreate a DaemonConfig with a largeCNILogFile\nstring.\nThis will create a large template.\nThe failure can happen at the moment the template is created in case its size is enough to\nexhaust memory, or later in the CNI merging process.\n2.\nThe existing CNI configuration file is large. Once its contents are merged with the template,\nthis may exhaust memory.\nRecommendation\nWe acknowledge that this code does not constitute a bug at the moment. However, we recommend\neither leaving a comment in the code that highlights the unbounded memory allocations are in fact\nsafe, or, add upper bounds to the template size and the existing CNI configuration file before\nreading it.\n27Cilium security audit, 2022\n5: Possible excessive memory allocation\nOverall severity:\nInformational\nID:\nADA-CIL-5\nLocation:\nhttps://github.com/cilium/cilium/blob/dac4c0691c2fd611308b28ed08 \nb8ba2ee7f38b8c/pkg/labels/labels.go#L478\nCWE:\n\u25cf\nCWE-400: Uncontrolled Resource Consumption\nDescription\nCilium may be made to create a byte slice that exceeds the memory available on the machine inlabels.SortedList()\n:\nfunc(l Labels)SortedList() []byte{keys :=make([]string,0,len(l))fork :=rangel {keys =append(keys, k)}sort.Strings(keys)\nb := make([]byte, 0, len(keys)*2)buf := bytes.NewBuffer(b)for_, k :=rangekeys {buf.Write(l[k].FormatForKVStore())}\nreturnbuf.Bytes()}\nIn similar fashion to issue 4, we did not find this to be vulnerable at this given moment, but we\nhighlight it as a potential issue since unbounded memory allocations can lead to memory\nexhaustion. It is worth noting here that according to\nhttps://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#syntax-and-character\n-set\nlabels are constrained in size, label keys <\n63 characters, but with a < 253 char potential prefix,\nvalues < 63 characters. Generously: below 400 ASCII characters, hence <400 bytes per label.\n28Cilium security audit, 2022\n6: Race condition in Hubble Relay Peer Manager\nOverall severity:\nLow\nID:\nADA-CIL-6\nLocation:\nhttps://github.com/cilium/cilium/blob/82c742f2e9fb65fb3fc392c7dcb3b4e22\nb69c650/pkg/hubble/relay/pool/manager.go#L143-L186\nCWE:\n\u25cf\nCWE-362: Concurrent Execution using Shared Resource with \nImproper Synchronization ('Race Condition')\nFix:\nhttps://github.com/cilium/cilium/commit/43121d9d554604f708eb273d117b6 \n8960747812d\nDescriptionPeerManager.manageConnections()\ncreates a goroutine\ninside a loop and references a\nvariable outside the goroutine. This can result in a race condition, whereby both the PeerManager\nand the peer name might change between they are declared and the time they are used inside the\ngoroutine:\nhttps://github.com/cilium/cilium/blob/82c742f2e9fb65fb3fc392c7dcb3b4e22b69c650/pkg/hubble/relay/poo\nl/manager.go#L143-L186\nfunc(m *PeerManager)manageConnections() {connTimer, connTimerDone := inctimer.New()deferconnTimerDone()for{select{case<-m.stop:returncasename := <-m.offline:m.mu.RLock()p := m.peers[name]m.mu.RUnlock()m.wg.Add(1)gofunc() {deferm.wg.Done()// a connection request has been made, make sureto attempta connectionm.connect(p, true)}()case<-connTimer.After(m.opts.connCheckInterval):m.mu.RLock()now := time.Now()for_, p :=rangem.peers {p.mu.Lock()ifp.conn !=nil{switchp.conn.GetState() {caseconnectivity.Connecting, connectivity.Idle,connectivity.Ready, connectivity.Shutdown:p.mu.Unlock()continue}\n29Cilium security audit, 2022\n}switch{casep.nextConnAttempt.IsZero(),p.nextConnAttempt.Before(now):p.mu.Unlock()m.wg.Add(1)gofunc() {deferm.wg.Done()m.connect(p, false)}()default:p.mu.Unlock()}}m.mu.RUnlock()}}}\nMinimal reproducer\nThe race condition is demonstrated with this reproducer that mimics the behaviour ofmanageConnections()\n.\nTowards the end of the program,\na line with a panic is marked with\nyellow. This panic will only be triggered iffirstPeerName\nandsecondPeerName\nare di\ufb00erent, ie.\nif the\np\nchanges before it is used inside the goroutine.\npackagemain\nimport(\"fmt\"\"github.com/cilium/cilium/pkg/lock\"\"sync\")\ntypepeerstruct{mu lock.Mutexnamestring}\ntypemstruct{mu lock.RWMutexwg sync.WaitGrouppeersmap[string]*peer}\nfunc(m *m)connect(p *peer) {fmt.Println(p.name)}\nfuncmain() {peers :=map[string]*peer{\"peer1\": &peer{name:\"peer1\"},\"peer2\": &peer{name:\"peer2\"},\"peer3\": &peer{name:\"peer3\"},\n30Cilium security audit, 2022\n\"peer4\": &peer{name:\"peer4\"},\"peer5\": &peer{name:\"peer5\"},\"peer6\": &peer{name:\"peer6\"},\"peer7\": &peer{name:\"peer7\"},\"peer8\": &peer{name:\"peer8\"},\"peer9\": &peer{name:\"peer9\"},\"peer510\": &peer{name:\"peer10\"},}m := &m{peers: peers}m.mu.RLock()for_, p :=rangem.peers {p.mu.Lock()p.mu.Unlock()m.wg.Add(1)gofunc() {deferm.wg.Done()firstPeerName := fmt.Sprintf(\"%s\", p.name)secondPeerName := fmt.Sprintf(\"%s\", p.name)ifsecondPeerName != firstPeerName {panic(fmt.Sprintf(\"We won the race:\\n'p.name'is %s and'firstPeerName' is %s\\n\", p.name, firstPeerName))}m.connect(p)}()fmt.Println(\"End of loop\")}m.mu.RUnlock()}\nFor more info, see\nE\ufb00ective Go: goroutines\n.\n31Cilium security audit, 2022\n7: Race condition inpkg/policy.Repository.LocalEndpointIdentityRemoved()\nOverall severity:\nLow\nID:\nADA-CIL-7\nLocation:\n\u25cf\nhttps://github.com/cilium/cilium/blob/bbcadc43758b7e3c89d0ef9a3\n9266\ufb00f1bc41849/pkg/policy/repository.go#L404\n\u25cf\nhttps://github.com/cilium/cilium/blob/314ca7bae\ufb004f568\ufb00c0bad9512\n4e40665b1f88c/pkg/identity/identitymanager/manager.go#L150\nCWE:\n\u25cf\nCWE-362: Concurrent Execution using Shared Resource with \nImproper Synchronization ('Race Condition')\nDescription\nAnother case of creating a goroutine and using a variable inside the goroutine that was declared\noutside of the goroutine exists inpkg/policy.Repository.LocalEndpointIdentityRemoved()\n.\n(*Repository).LocalEndpointIdentityRemoved()\ncreates\na goroutine:\nfunc(p *Repository)LocalEndpointIdentityRemoved(identity*identity.Identity) {gofunc() {scopedLog := log.WithField(logfields.Identity, identity)scopedLog.Debug(\"Removing identity references frompolicy cache\")p.Mutex.RLock()wg := p.removeIdentityFromRuleCaches(identity)wg.Wait()p.Mutex.RUnlock()scopedLog.Debug(\"Finished cleaning policy cache\")}()}\nLocalEndpointIdentityRemoved()\nis called here:\nhttps://github.com/cilium/cilium/blob/master/pkg/identity/identitymanager/manager.go\nfunc(idm *IdentityManager)remove(identity *identity.Identity){\nifidentity ==nil{return}\nidMeta, exists := idm.identities[identity.ID]if!exists {log.WithFields(logrus.Fields{logfields.Identity: identity,}).Error(\"removing identity not added to the identitymanager!\")\n32Cilium security audit, 2022\nreturn}idMeta.refCount--ifidMeta.refCount ==0{delete(idm.identities, identity.ID)foro :=rangeidm.observers {o.LocalEndpointIdentityRemoved(identity)}}\n}\nThe for-loop (marked with blue) loops through all observers of the identitymanager, and starts a\ngoroutine in each iteration. This will not always start one goroutine for each observer but might\nstart multiple goroutines for the same observer.\nFor more info, see\nE\ufb00ective Go: goroutines\n.\n33Cilium security audit, 2022\n8: Deprecated 3rd-party library\nOverall severity:\nInformational\nID:\nADA-CIL-8\nLocation:\n\u25cf\nhttps://github.com/cilium/cilium/blob/3f6dadc91c92bdf09a5dfaedb\n93047dc9f764cc3/tools/tools.go#L11\nCWE:\n\u25cf\nCWE-477: Use of Obsolete Function\nDescription:\nCilium has in its dependency treegithub.com/gogo/protobuf\nwhich is deprecated. We\nrecommend discontinuing all use of deprecated dependencies.\nKubernetes also relies on this library:\nhttps://github.com/kubernetes/kubernetes/issues/96564\n,\nand since Cilium uses kubernetes libraries, Cilium cannot remove this dependency until k8s does it.\n34Cilium security audit, 2022\n9: TOCTOU race condition in endpoint file move helper function\nOverall severity:\nLow\nID:\nADA-CIL-9\nLocation:\n\u25cf\nhttps://github.com/cilium/cilium/blob/314ca7bae\ufb004f568\ufb00c0bad9512\n4e40665b1f88c/pkg/endpoint/directory.go#L50\nCWE:\n\u25cf\nCWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition\nDescription\nA TOCTOU race condition exists in pkg/endpoint when moving files from one directory to another.\nhttps://github.com/cilium/cilium/blob/314ca7bae\ufb004f568\ufb00c0bad95124e40665b1f88c/pkg/endpoint\n/directory.go#L50\nfuncmoveNewFilesTo(oldDir, newDirstring)error{oldFiles, err := os.ReadDir(oldDir)iferr !=nil{returnerr}newFiles, err := os.ReadDir(newDir)iferr !=nil{returnerr}\nfor_, oldFile :=rangeoldFiles {exists :=falsefor_, newFile :=rangenewFiles {ifoldFile.Name() == newFile.Name() {exists =truebreak}}if!exists {os.Rename(filepath.Join(oldDir,oldFile.Name()),filepath.Join(newDir,oldFile.Name()))}}returnnil}\nThis could be exploited if an attacker can replace a file in oldDir a\u0000er oldDir has been read and\nbefore the file is renamed.\nThe issue could potentially allow users to create files in directories that they should not be able to\ncreate files in.\nThis issue is ratedLOW\n, because an attacker with\nthis level of access can trigger the impact\nregardless of the TOCTOU race condition.\n35Cilium security audit, 2022\nTo replace a file in oldDir, the adversary already needs unix permissions to create/delete files in\nthat directory. If that is given, they can just create a file in oldDir, which will then be moved to\nnewDir if there is no file name conflict.\u201d\n36Cilium security audit, 2022\n10: Redundant return statements\nOverall severity:\nInformational\nID:\nADA-CIL-10\nLocation:\nSeveral packages\nCWE:\n\u25cf\nCWE-1041: Use of Redundant Code\nDescription\nhttps://github.com/cilium/cilium/blob/314ca7bae\ufb004f568\ufb00c0bad95124e40665b1f88c/cilium/cmd/debuginfo.go#L346\nfuncwriteJSONPathToOutput(buf bytes.Buffer, pathstring, suffixstring, jsonPathstring){data := buf.Bytes()db := &models.DebugInfo{}err := db.UnmarshalBinary(data)iferr !=nil{fmt.Fprintf(os.Stderr,\"error unmarshaling binary:%s\\n\", err)}jsonStr, err := command.DumpJSONToString(db, jsonPath)iferr !=nil{fmt.Fprintf(os.Stderr,\"error printing JSON: %s\\n\",err)}\nifpath ==\"\"{fmt.Println(jsonStr)return}\nfileName := fileName(path, suffix)writeFile([]byte(jsonStr), fileName)\nfmt.Printf(\"%s output at %s\\n\", jsonpathOutput, fileName)return}\nhttps://github.com/cilium/cilium/blob/00e40bb41683b9b3462a94879a93841751197629/daemon/cmd/config.go#L33\nfunc(h *patchConfig)configModify(params PatchConfigParams,resChanchaninterface{}) {...d.TriggerDatapathRegen(policyEnforcementChanged,\"agent configurationupdate\")}\nresChan <- NewPatchConfigOK()return}\nhttps://github.com/cilium/cilium/blob/de82f8c1a3cb92cde0f37fe627aaf1c313a37caf/daemon/cmd/policy.go#L430\nfunc(d *Daemon)policyAdd(sourceRules policyAPI.Rules,opts *policy.AddOptions, resChanchaninterface{}) {\n37Cilium security audit, 2022\n..._, err = d.policy.RuleReactionQueue.Enqueue(ev)iferr !=nil{log.WithError(err).WithField(logfields.PolicyRevision,newRev).Error(\"enqueue of RuleReactionEvent failed\")}\nreturn}\nhttps://github.com/cilium/cilium/blob/de82f8c1a3cb92cde0f37fe627aaf1c313a37caf/daemon/cmd/policy.go#L644\nfunc(d *Daemon)policyDelete(labels labels.LabelArray,reschaninterface{}) {if_, err := d.policy.RuleReactionQueue.Enqueue(ev);err !=nil{log.WithError(err).WithField(logfields.PolicyRevision, rev).Error(\"enqueueof RuleReactionEvent failed\")}iferr := d.SendNotification(monitorAPI.PolicyDeleteMessage(deleted,labels.GetModel(), rev)); err !=nil{log.WithError(err).WithField(logfields.PolicyRevision, rev).Warn(\"Failedto send policy update as monitor notification\")}\nreturn}\nhttps://github.com/cilium/cilium/blob/b1aa5374acf77a598e8f5a6d69cbc53122812d62/daemon/cmd/status.go#L1093\nfunc(d *Daemon)startStatusCollector(cleaner *daemonCleanup){...cleaner.cleanupFuncs.Add(func() {// If the KVstore state is not OK, print help foruser.ifd.statusResponse.Kvstore !=nil&&d.statusResponse.Kvstore.State != models.StatusStateOk {helpMsg :=\"cilium-agent depends on the availabilityofcilium-operator/etcd-cluster. \"+\"Check if the cilium-operator pod and etcd-clusterarerunning and do not have any \"+\"warnings or error messages.\"log.WithFields(logrus.Fields{\"status\": d.statusResponse.Kvstore.Msg,logfields.HelpMessage: helpMsg,}).Error(\"KVStore state not OK\")\n}})return}\nhttps://github.com/cilium/cilium/blob/c147bbd3211f0ef19eb13f4daab07e100e6b72d5/operator/pkg/ciliumendpointslic\ne/endpointslice.go#L173\nfuncsyncCESsInLocalCache(cesStore cache.Store, manageroperations) {...log.Debug(\"Successfully synced all CESs locally\")\n38Cilium security audit, 2022\nreturn}\nhttps://github.com/cilium/cilium/blob/c147bbd3211f0ef19eb13f4daab07e100e6b72d5/operator/pkg/ciliumendpointslic\ne/endpointslice.go#L196\nfunc(c *CiliumEndpointSliceController)Run(ces cache.Indexer,stopChchanstruct{}) {...gowait.Until(c.worker, c.workerLoopPeriod, stopCh)\ngofunc() {deferutilruntime.HandleCrash()}()\n<-stopCh\nreturn}\nhttps://github.com/cilium/cilium/blob/c147bbd3211f0ef19eb13f4daab07e100e6b72d5/operator/pkg/ciliumendpointslic\ne/endpointslice.go#L217\nfuncsyncCESsInLocalCache(cesStore cache.Store, manageroperations) {...log.Debug(\"Successfully synced all CESs locally\")return}\nhttps://github.com/cilium/cilium/blob/e4ea0fa10af293b24fbe6b26307ec2709bb856e6/operator/pkg/ciliumendpointslice\n/manager.go#L168\nfunc(c *cesMgr)addCEPtoCES(cep *cilium_v2.CoreCiliumEndpoint,ces *cesTracker) {...// Increment the cepInsert counterces.cepInserted +=1c.insertCESInWorkQueue(ces, DefaultCESSyncTime)return}\nhttps://github.com/cilium/cilium/blob/e4ea0fa10af293b24fbe6b26307ec2709bb856e6/operator/pkg/ciliumendpointslice\n/manager.go#L367\nfunc(c *cesMgr)RemoveCEPFromCache(cepNamestring,baseDelay time.Duration) {...}else{log.WithFields(logrus.Fields{logfields.CEPName: cepName,}).Info(\"Attempted to retrieve non-existent CES,skip processing.\")}\nreturn}\n39Cilium security audit, 2022\nhttps://github.com/cilium/cilium/blob/0b7919a9d8138a42dc82f3861372c665970fd22c/pkg/alibabacloud/eni/node.go#L\n86\nfunc(n *Node)PopulateStatusFields(resource *v2.CiliumNode){resource.Status.AlibabaCloud.ENIs =map[string]eniTypes.ENI{}\nn.manager.ForeachInstance(n.node.InstanceID(),func(instanceID, interfaceIDstring, rev ipamTypes.InterfaceRevision)error{e, ok := rev.Resource.(*eniTypes.ENI)ifok {resource.Status.AlibabaCloud.ENIs[interfaceID] =*e.DeepCopy()}returnnil})\nreturn}\nhttps://github.com/cilium/cilium/blob/c5cbf403dbe355ecbb80dfc8d7a8ed4da45c43bd/pkg/aws/eni/node.go#L105\nfunc(n *Node)PopulateStatusFields(k8sObj *v2.CiliumNode){k8sObj.Status.ENI.ENIs =map[string]eniTypes.ENI{}\nn.manager.ForeachInstance(n.node.InstanceID(),func(instanceID, interfaceIDstring, rev ipamTypes.InterfaceRevision)error{e, ok := rev.Resource.(*eniTypes.ENI)ifok {k8sObj.Status.ENI.ENIs[interfaceID] = *e.DeepCopy()}returnnil})\nreturn}\nhttps://github.com/cilium/cilium/blob/f3a4c4d204cf84af3d40f4782aa68e7c2da98440/pkg/endpoint/events.go#L68\nfunc(ev *EndpointRegenerationEvent)Handle(reschaninterface{}) {...res <- &EndpointRegenerationResult{err: err,}return}\nhttps://github.com/cilium/cilium/blob/f3a4c4d204cf84af3d40f4782aa68e7c2da98440/pkg/endpoint/events.go#L185\nfunc(ev *EndpointNoTrackEvent)Handle(reschaninterface{}){...res <- &EndpointRegenerationResult{err:nil,\n40Cilium security audit, 2022\n}return}\nhttps://github.com/cilium/cilium/blob/f3a4c4d204cf84af3d40f4782aa68e7c2da98440/pkg/endpoint/events.go#L251\nfunc(ev *EndpointPolicyVisibilityEvent)Handle(reschaninterface{}) {...e.visibilityPolicy = nvpres <- &EndpointRegenerationResult{err:nil,}return}\nhttps://github.com/cilium/cilium/blob/c112a3e59dcc988cf3a9901b48bce9583cfb3581/pkg/ipam/allocator/podcidr/podc\nidr.go#L420\nfunc(n *NodesPodCIDRManager)Delete(node *v2.CiliumNode){...n.ciliumNodesToK8s[node.Name] = &ciliumNodeK8sOp{op: k8sOpDelete,}n.k8sReSync.Trigger()return}\nhttps://github.com/cilium/cilium/blob/295d32957db4defae2c1dc594\ufb009b284c6513d4f/pkg/maps/lbmap/ipv4.go#L224\nfunc(in *pad2uint8)DeepCopyInto(out *pad2uint8){copy(out[:], in[:])return}\nhttps://github.com/cilium/cilium/blob/d5227f1baed6eb56865dc08275e6560b\ufb00f27cce/pkg/maps/lxcmap/lxcmap.go#L11\n3\nfunc(in *pad4uint32)DeepCopyInto(out *pad4uint32){copy(out[:], in[:])return}\nhttps://github.com/cilium/cilium/blob/314ca7bae\ufb004f568\ufb00c0bad95124e40665b1f88c/pkg/tuple/tuple.go#L42\nfunc(in *buff256uint8)DeepCopyInto(out *buff256uint8){copy(out[:], in[:])return}\nhttps://github.com/cilium/cilium/blob/5fc05ac07597ed651a8ccb2e59dc73691ec2caec/pkg/types/ipv4.go#L32\nfunc(v4 *IPv4)DeepCopyInto(out *IPv4) {copy(out[:], v4[:])return\n41Cilium security audit, 2022\n}\nhttps://github.com/cilium/cilium/blob/5fc05ac07597ed651a8ccb2e59dc73691ec2caec/pkg/types/ipv6.go#L30\nfunc(v6 *IPv6)DeepCopyInto(out *IPv6) {copy(out[:], v6[:])return}\nhttps://github.com/cilium/cilium/blob/314ca7bae\ufb004f568\ufb00c0bad95124e40665b1f88c/pkg/types/macaddr.go#L24\nfunc(addr *MACAddr)DeepCopyInto(out *MACAddr) {copy(out[:], addr[:])return}\n42Cilium security audit, 2022\n11: Redundant imports\nOverall severity:\nInformational\nID:\nADA-CIL-11\nLocation:\nSeveral packages\nCWE:\n\u25cf\nCWE-1041: Use of Redundant Code\nDescription\nCilium imports the same library twice in the same file these places of the source tree:\nFile\nDouble import\ndaemon/cmd/daemon.gogithub.com/cilium/cilium/pkg/k8s/client\ndaemon/cmd/daemon_main.gogithub.com/cilium/cilium/pkg/wireguard/agent\noperator/cmd/flags.gogithub.com/cilium/cilium/pkg/option\noperator/pkg/ciliumendpointslice/endpointslice.gogithub.com/cilium/cilium/pkg/k8s/apis/cilium.io/v2alpha1\npkg/k8s/watchers/cilium_endpoint_slice.gogithub.com/cilium/cilium/pkg/k8s/apis/cilium.io/v2alpha1\npkg/k8s/watchers/cilium_network_policy.gogithub.com/cilium/cilium/pkg/k8s/utils\npkg/nodediscovery/nodediscovery.gogithub.com/cilium/cilium/pkg/node/types\npkg/redirectpolicy/redirectpolicy.gogithub.com/cilium/cilium/pkg/loadbalancer\npkg/service/service.gogithub.com/cilium/cilium/pkg/datapath/types\n43Cilium security audit, 2022\n12: Redundant function parameters\nOverall severity:\nInformational\nID:\nADA-CIL-12\nLocation:\nSeveral packages\nCWE\n\u25cf\nCWE-1041: Use of Redundant Code\nDescription\nThis issue lists the places in which Cilium passes a function parameter that remains unused in the\nfunction body rendering the parameter redundant.\nLatest commit of this check:b8a6791299083d9888819d03f458ecd1942abf81\nFile\nAPI\nParam name\napi/v1/server/configure_cilium_api.goconfigureServerscheme, addr\ndaemon/cmd/ciliumendpoints.go(*Daemon).deleteCiliumEndpointeps\ndaemon/cmd/daemon_main.go(*Daemon).instantiateBGPControlPlanectx\ndaemon/cmd/hubble.gogetHubbleEventBufferCapacitylogger\noperator/pkg/lbipam/lbipam.go(*LBIPAM).poolOnUpsertk\noperator/pkg/lbipam/lbipam.go(*LBIPAM).poolOnDeletek\noperator/pkg/lbipam/lbipam.go(*LBIPAM).svcOnUpsertk\noperator/pkg/lbipam/lbipam.go(*LBIPAM).svcOnDeletek\npkg/alibabacloud/eni/node.go(*Node).getSecurityGroupIDsctx\npkg/aws/eni/migration.go(*InterfaceDB).fetchFromK8sname\npkg/aws/eni/node.go(*Node).getSecurityGroupIDsctx\npkg/bgp/manager/metallb.gonewMetalLBControllerctx\npkg/bgp/speaker/metallb.gonewMetalLBSpeakerctx\npkg/bgpv1/gobgp/routermgr.go(*BGPRouterManager).withdrawctx\npkg/bgpv1/gobgp/workdiff.go(*reconcileDiff).withdrawDiffpolicy\npkg/bpf/map_linux.go(*Map).deleteAllMapEventerr\npkg/bpf/map_register_linux.gounregisterMapm\npkg/datapath/ipcache/listener.go(*BPFListener).garbageCollectctx\npkg/datapath/iptables/iptables.go(*IptablesManager).installMasqueradeRulesifName\n44Cilium security audit, 2022\npkg/datapath/linux/routing/migrate.go(*migrator).copyRoutesfrom\npkg/datapath/loader/loader.go(*Loader).replaceNetworkDatapathinterfaces\npkg/egressgateway/net.goaddEgressIpRuleegressIP\npkg/ipam/allocator/podcidr/podcidr.gogetCIDRAllocatorsInfonetTypes\npkg/ipam/node_manager.go(*NodeManager).resyncNodectx\npkg/k8s/apis/cilium.io/client/register.gowaitForV1CRDcrdName\npkg/k8s/apis/cilium.io/client/v1beta1.gowaitForV1beta1CRDcrdName\npkg/k8s/identitybackend/identity.go(*crdBackend).getctx\npkg/k8s/identitybackend/identity.go(*crdBackend).getByIdctx\npkg/k8s/watchers/cilium_clusterwide_envoy_config.go(*K8sWatcher).ciliumClusterwideEnvoyConfigInitclientset\npkg/k8s/watchers/endpoint.go(*K8sWatcher).updateK8sEndpointV1oldEP\npkg/k8s/watchers/service.go(*K8sWatcher).updateK8sServiceV1oldSvc\npkg/k8s/watchers/watcher.go(*K8sWatcher).enableK8sWatchersctx\npkg/k8s/watchers/watcher.go(*K8sWatcher).delK8sSVCsse\npkg/monitor/agent/agent.go(*Agent).processPerfRecordscopedLog\npkg/monitor/api/drop.goextendedReasonreason\npkg/monitor/format/format.go(*MonitorFormatter).policyVerdictEventsprefix\npkg/monitor/format/format.go(*MonitorFormatter).recorderCaptureEventsprefix\npkg/monitor/format/format.go(*MonitorFormatter).logRecordEventsprefix\npkg/monitor/format/format.go(*MonitorFormatter).agentEventsprefix\npkg/node/address.gochooseHostIPsToRestoreipv6\npkg/pidfile/pidfile.gokillpidfile\npkg/policy/selectorcache.go(*selectorManager).removeUserdnsProxy\npkg/proxy/dns.go(*dnsRedirect).setRuleswg\nproxylib/proxylib/policymap.gonewPortNetworkPolicyRulesport\n45Cilium security audit, 2022\n13: TOCTOU race condition in sockopsbpftoolLoad\nOverall severity:\nLow\nID:\nADA-CIL-13\nLocation:pkg/sockops\nCWE:\n\u25cf\nCWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition\nFix:\nhttps://github.com/cilium/cilium/pull/23606\nDescription\nA TOCTOU race condition exists in sockopsbpftoolLoad\n.\nhttps://github.com/cilium/cilium/blob/473e75f4d49b6e47880833e041c946b5446a145d/pkg/sockops/sockops.go#L100\nfuncbpftoolLoad(bpfObjectstring, bpfFsFilestring)error{...maps, err := os.ReadDir(filepath.Join(bpf.GetMapRoot(),\"/tc/globals/\"))iferr !=nil{returnerr}\nfor_, f :=rangemaps {// Ignore all backing filesifstrings.HasPrefix(f.Name(),\"..\") {continue}\nuse :=func()bool{for_, n :=rangesockopsMaps {iff.Name() == n {returntrue}}returnfalse}()\nif!use {continue}\nmapString := []string{\"map\",\"name\", f.Name(),\"pinned\",filepath.Join(bpf.GetMapRoot(),\"/tc/globals/\", f.Name())}mapArgList =append(mapArgList, mapString...)}\nargs := []string{\"-m\",\"prog\",\"load\", bpfObject,bpffs}args =append(args, mapArgList...)log.WithFields(logrus.Fields{\"bpftool\": prog,\"args\": args,}).Debug(\"Load BPF Object:\")out, err := exec.Command(prog, args...).CombinedOutput()\n46Cilium security audit, 2022\niferr !=nil{returnfmt.Errorf(\"Failed to load %s: %s: %s\", bpfObject,err, out)}returnnil}\nIn this API there is a check whether a map should be used. If it should, then the map is referenced\nby name and passed to the bp\u0000ool. A race condition exists in that the map could be replaced a\u0000er\nthe check has occurred and before bp\u0000ool is invoked.\nThe specific part that has the race condition is this:\nuse :=func()bool{for_, n :=rangesockopsMaps {iff.Name() == n {returntrue}}returnfalse}()\nif!use {continue}\nmapString := []string{\"map\",\"name\", f.Name(),\"pinned\",filepath.Join(bpf.GetMapRoot(),\"/tc/globals/\", f.Name())}mapArgList =append(mapArgList, mapString...)\nThe level of exploitability of this issue is low but is included here to highlight that there currently is\nnot a guarantee that the map that Cilium loads is the map that it - or the user - expects to load.\n47Cilium security audit, 2022\n14: Level of trust for input from cloud providers is too high\nOverall severity:\nLow\nID:\nADA-CIL-14\nLocation:\n\u25cfpkg/azure\n\u25cfpkg/alibabacloud\n\u25cfpkg/aws\nCWE:\n\u25cf\nCWE-1041: Use of Redundant Code\nFix:\nhttps://github.com/cilium/cilium/pull/22602\nDescription\nWhen Cilium fetches metadata from a 3rd party, Azure IMS, Alibaba Cloud, AWS, the response is\nread entirely into memory without enforcing an upper limit. Since Cilium does not control the\nbehavior of these 3rd-party APIs, it cannot ensure that the size of the response will always be\nwithin reasonable limits. If an attacker finds a way to generate a response that contains a large\nbody, a Denial-of-Service scenario would exist, when Cilium reads the entire response into\nmemory.\nThe scenario exists the following places:\nAzure IMS\nhttps://github.com/cilium/cilium/blob/314ca7bae\ufb004f568\ufb00c0bad95124e40665b1f88c/pkg/azure/ap\ni/metadata.go#L39\nfuncgetMetadataString(ctx context.Context, pathstring)(string, error) {client := &http.Client{Timeout: time.Second *10,}url := fmt.Sprintf(\"%s/%s\", metadataURL, path)req, err := http.NewRequestWithContext(ctx, http.MethodGet, url,nil)iferr !=nil{return\"\",nil}\nquery := req.URL.Query()query.Add(\"api-version\", metadataAPIVersion)query.Add(\"format\",\"text\")\nreq.URL.RawQuery = query.Encode()req.Header.Add(\"Metadata\",\"true\")\nresp, err := client.Do(req)iferr !=nil{return\"\", err}deferfunc() {\n48Cilium security audit, 2022\niferr := resp.Body.Close(); err !=nil{log.WithError(err).Errorf(\"Failed to close bodyfor request %s\",url)}}()\nrespBytes, err := io.ReadAll(resp.Body)iferr !=nil{return\"\", err}\nreturnstring(respBytes),nil}\nAlibaba Cloud\nhttps://github.com/cilium/cilium/blob/181b030b0dd868091cc00d0bd8b1ce40688d63ae/pkg/aliba\nbacloud/metadata/metadata.go#L50\nfuncgetMetadata(ctx context.Context, pathstring)(string, error) {client := &http.Client{Timeout: time.Second *10,}url := fmt.Sprintf(\"%s/%s\", metadataURL, path)req, err := http.NewRequestWithContext(ctx, http.MethodGet, url,nil)iferr !=nil{return\"\", err}\nresp, err := client.Do(req)iferr !=nil{return\"\", err}\nifresp.StatusCode != http.StatusOK {return\"\", fmt.Errorf(\"metadata service returnedstatus code %d\",resp.StatusCode)}\ndeferresp.Body.Close()respBytes, err := io.ReadAll(resp.Body)iferr !=nil{return\"\", err}\nreturnstring(respBytes),nil}\nAWS\nhttps://github.com/cilium/cilium/blob/c5cbf403dbe355ecbb80dfc8d7a8ed4da45c43bd/pkg/aws/\nmetadata/metadata.go#L24\nfuncgetMetadata(client *imds.Client, pathstring)(string, error) {res, err := client.GetMetadata(context.TODO(), &imds.GetMetadataInput{Path: path,\n49Cilium security audit, 2022\n})iferr !=nil{return\"\", fmt.Errorf(\"unable to retrieve AWS metadata%s: %w\", path, err)}\ndeferres.Content.Close()value, err := io.ReadAll(res.Content)iferr !=nil{return\"\", fmt.Errorf(\"unable to read response contentfor AWS metadata%q: %w\", path, err)}\nreturnstring(value), err}\n50Cilium security audit, 2022\n15: BGP configuration file is read entirely into memory\nOverall severity\nLow\nID:\nADA-CIL-15\nLocation:pkg/bgp\nCWE:\n\u25cf\nCWE-1041: Use of Redundant Code\nFix:\nhttps:/ /github.com/cilium/cilium/pull/22602\nDescription\nThe BGP config parser reads a config file entirely into memory. This could create a scenario\nwhereby a malicious user intentionally - or a genuine user unintentionally - could parse a config file\nthat is larger than the available memory on the memory creating Denial-of-Service of the machine.\nhttps://github.com/cilium/cilium/blob/314ca7bae\ufb004f568\ufb00c0bad95124e40665b1f88c/pkg/bgp/conf\nig/config.go#L16\nfuncParse(r io.Reader) (*metallbcfg.Config, error){buf, err := io.ReadAll(r)iferr !=nil{returnnil, fmt.Errorf(\"failed to read MetalLB config:%w\", err)}config, err := metallbcfg.Parse(buf)iferr !=nil{returnnil, fmt.Errorf(\"failed to parse MetalLBconfig: %w\", err)}returnconfig,nil}\n51Cilium security audit, 2022\n16: Race condition when starting operator apiserver\nOverall severity:\nLow\nID:\nADA-CIL-16\nLocation:\nOperator apiserver\nCWE:\n\u25cf\nCWE-362: Concurrent Execution using Shared Resource with \nImproper Synchronization ('Race Condition')\nDescription\nA race condition exists when starting the oprerator apiserver.StartServer()\nloops through all\naddresses ins.listenAddres\nand starts a goroutine\nin each iteration. Each goroutine refers to\naddr which is not passed to the goroutine. As such, the addr in each goroutine may not be the addr\nof the given loop iteration.\nThis is purely a cosmetic issue with the highest impact of causing confusion when going through\nthe logs.\nfunc(s *Server)StartServer()error{errs :=make(chanerror,1)nServers :=0\n// Since we are opening this on localhost only, weneed to make sure// we can open for both v4 and v6 localhost. In casethe user is running// v4-only or v6-only.for_,addr:=ranges.listenAddrs {ifaddr ==\"\"{continue}nServers++\nmux := http.NewServeMux()\n// Index handler is the the handler for Open-APIrouter.mux.Handle(\"/\", s.Server.GetHandler())// Create a custom handler for /healthz as an aliasto /v1/healthz. A httpmux// is required for this because open-api spec doesnot allow multiple basepaths// to be specified.mux.HandleFunc(\"/healthz\",func(rw http.ResponseWriter,_ *http.Request) {resp := s.healthzHandler.Handle(operator.GetHealthzParams{})resp.WriteResponse(rw, runtime.TextProducer())})\nsrv := &http.Server{Addr: addr,Handler: mux,}\n52Cilium security audit, 2022\nerrCh :=make(chanerror,1)\nlc := net.ListenConfig{Control: setsockoptReuseAddrAndPort}ln, err := lc.Listen(context.Background(),\"tcp\",addr)iferr !=nil{log.WithError(err).Fatalf(\"Unable to listen on%s for healthzapiserver\", addr)}\ngofunc() {err := srv.Serve(ln)iferr !=nil{// If the error is due to the server being shutdown,thensend nil to// the server errors channel.iferrors.Is(err, http.ErrServerClosed) {log.WithField(\"address\",addr).Debug(\"OperatorAPIserver closed\")errs <-nil}else{errCh <- errerrs <- err}}}()\ngofunc() {select{case<-s.shutdownSignal:iferr := srv.Shutdown(context.Background());err !=nil{log.WithError(err).Error(\"apiserver shutdown\")}caseerr := <-errCh:log.WithError(err).Warn(\"Unable to start operatorAPIserver\")}}()\nlog.Infof(\"Starting apiserver on address %s\", addr)}\nvarretErr errorforerr :=rangeerrs {iferr !=nil{retErr = err}\nnServers--ifnServers ==0{returnretErr}}\nreturnnil}\n53Cilium security audit, 2022\n17: Bad code practice: Identical identifier of import and variable\nOverall severity:\nLow\nID:\nADA-CIL-17\nLocation:pkg/egressgateway\nCWE:\n\u25cf\nCWE-1109: Use of Same Variable for Multiple Purposes\nDescription\nOverwriting import identifiers could result in undefined behavior and should be avoided. In the\nfollowing part of Cilium, a variable is assigned to an identifier that also refers to an imported\npackage.\nhttps://github.com/cilium/cilium/blob/710297f229480bbd4fc52f39ea68a6eeb333c9d4/pkg/egressg\nateway/manager.go#L80\nfunc(manager *Manager)getIdentityLabels(securityIdentityuint32) (labels.Labels, error){identityCtx, cancel := context.WithTimeout(context.Background(),option.Config.KVstoreConnectivityTimeout)defercancel()iferr := manager.identityAllocator.WaitForInitialGlobalIdentities(identityCtx);err !=nil{returnnil, fmt.Errorf(\"failed to wait for initialglobal identities: %v\",err)}\nidentity:= manager.identityAllocator.LookupIdentityByID(identityCtx,identity.NumericIdentity(securityIdentity))ifidentity ==nil{returnnil, fmt.Errorf(\"identity %d not found\",securityIdentity)}returnidentity.Labels,nil}\nWhere this package is imported:github.com/cilium/cilium/pkg/identity\n.\nRecommendations\nChange the variable identifier.\n54Cilium security audit, 2022\n18: Deadlock from locked mutex\nOverall severity:\nMedium\nID:\nADA-CIL-18\nLocation:pkg/envoy\nCWE:\n\u25cf\nCWE-667: Improper Locking\nFix:\nhttps://github.com/cilium/cilium/pull/23077\nDescription\nGo has two common tools when dealing with concurrency: Mutual exclusion - also known as\nmutex, and channels. A mutex is a low-level tool to protect against race conditions. A mutex can be\neither locked or unlocked. A mutex can perform two operations: Lock and unlock. Each operation is\natomic, meaning that a process has to wait for a locked process to be unlocked until it itself can\nlock. If a process fails to unlock, other processes may wait for an unlock that does not happen\nresulting in a deadlock.\nCilium has a deadlock error in the envoy package from a missing mutex unlock before returning in\ncase of an invalidlistenerConfig\n:\nhttps://github.com/cilium/cilium/blob/79c6f5725372b52c9877a9bde1249da039948649/pkg/envoy/server.go#L576\niferr := listenerConfig.Validate(); err !=nil{log.Errorf(\"Envoy: Could not validate Listener (%s):%s\", err,listenerConfig.String())return}\nRecommendation\nUnlock thes.mutex\nbefore returning.\n55Cilium security audit, 2022\n19: Possible type confusions\nOverall severity:\nLow\nID:\nADA-CIL-19\nLocation:\nSeveral packages\nCWE:\n\u25cf\nCWE-704: Incorrect Type Conversion or Cast\n\u25cf\nCWE-843: Access of Resource Using Incompatible Type ('Type \nConfusion')\nDescription\nType confusions occur when a variable is assumed to be of a type that it is not. They are usually\nmore severe in memory-unsafe languages than in memory-safe languages like Go and are\nrecoverable in Go which only rarely makes them critical. However, there have been previous cases\nof type confusions in open source Go source code having security implications such as\nGHSA-qq97-vm5h-rrhg\n. In addition, Cilium has had issues\nin the past with panics from type\nconfusions:\nhttps://github.com/cilium/cilium/pull/171\n.\nIdeally all type assertions should either be checked or a unit test should demonstrate that the given\ncast is safe. Checking all casts would ensure that all casts are safe, but since this may unnecessarily\nbloat the production code base this may not be the best avenue. Instead, a unit test could catch\ntype confusions from being introduced from unchecked type assertions when the code base\nchanges.\nBelow we list the type assertions identified during this audit.\nhttps://github.com/cilium/cilium/blob/fd50b8d3b9684e0e88139e5776bd68ef15a344d0/cilium/cmd/bpf_ct_list.go#L122-\nL162\nfuncdumpCt(maps []interface{}, args ...interface{}){entries :=make([]ctmap.CtMapRecord,0)eID := args[0]\nfor_, m :=rangemaps {path, err :=m.(ctmap.CtMap).Path()iferr ==nil{err =m.(ctmap.CtMap).Open()}iferr !=nil{ifos.IsNotExist(err) {msg :=\"Unable to open %s: %s.\"ifeID.(string) !=\"global\"{msg =\"Unable to open %s: %s: please try using\\\"cilium bpf ct list global\\\".\"}fmt.Fprintf(os.Stderr, msg+\" Skipping.\\n\", path,err)continue\n56Cilium security audit, 2022\n}Fatalf(\"Unable to open %s: %s\", path, err)}deferm.(ctmap.CtMap).Close()// Plain output prints immediately, JSON/YAML outputholds until it// collected values from all maps to have one consistentobjectifcommand.OutputOption() {callback :=func(key bpf.MapKey, value bpf.MapValue){record := ctmap.CtMapRecord{Key:key.(ctmap.CtKey),Value:*value.(*ctmap.CtEntry)}entries =append(entries, record)}iferr =m.(ctmap.CtMap).DumpWithCallback(callback);err !=nil{Fatalf(\"Error while collecting BPF map entries:%s\", err)}}else{doDumpEntries(m.(ctmap.CtMap))}}ifcommand.OutputOption() {iferr := command.PrintOutput(entries); err !=nil{os.Exit(1)}}}\nhttps://github.com/cilium/cilium/blob/d5227f1baed6eb56865dc08275e6560b\ufb00f27cce/cilium/cmd/bpf_ipcache_get.go#L\n52\nv :=value.([]string)iflen(v) ==0{fmt.Printf(\"Unable to retrieve identity for LPMentry %s\\n\", arg)os.Exit(1)}\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/cilium/cmd/bpf_lb_list.go#L71-L8\n8\nparseBackendEntry :=func(key bpf.MapKey, value bpf.MapValue){id :=key.(lbmap.BackendKey).GetID()backendMap[id] = value.DeepCopyMapValue().(lbmap.BackendValue).ToHost()}iferr := lbmap.Backend4MapV3.DumpWithCallbackIfExists(parseBackendEntry);err !=nil{Fatalf(\"Unable to dump IPv4 backends table: %s\",err)}iferr := lbmap.Backend6MapV3.DumpWithCallbackIfExists(parseBackendEntry);err !=nil{Fatalf(\"Unable to dump IPv6 backends table: %s\",err)}\nparseSVCEntry :=func(key bpf.MapKey, value bpf.MapValue){varentrystring\n57Cilium security audit, 2022\nsvcKey :=key.(lbmap.ServiceKey)svcVal :=value.(lbmap.ServiceValue).ToHost()svc := svcKey.String()svcKey = svcKey.ToHost()\nhttps://github.com/cilium/cilium/blob/fd50b8d3b9684e0e88139e5776bd68ef15a344d0/cilium/cmd/bpf_nat_list.go#L60-\nL68\nifcommand.OutputOption() {callback :=func(key bpf.MapKey, value bpf.MapValue){record := nat.NatMapRecord{Key:key.(nat.NatKey),Value:value.(nat.NatEntry)}entries =append(entries, record)}iferr =m.(nat.NatMap).DumpWithCallback(callback);err !=nil{Fatalf(\"Error while collecting BPF map entries:%s\", err)}}else{out, err :=m.(nat.NatMap).DumpEntries()\nhttps://github.com/cilium/cilium/blob/e4d9dd21cfcb396bfe38893547bfe6ed578f7292/cilium/cmd/bpf_recorder_list.go#\nL57-L65\nifcommand.OutputOption() {callback :=func(key bpf.MapKey, value bpf.MapValue){record := recorder.MapRecord{Key:key.(recorder.RecorderKey), Value:value.(recorder.RecorderEntry)}entries =append(entries, record)}iferr = m.DumpWithCallback(callback); err !=nil{Fatalf(\"Error while collecting BPF map entries:%s\", err)}}else{\nhttps://github.com/cilium/cilium/blob/677750f8a3f098be7da6bb7b5a94c240e6633b36/operator/cmd/cilium_node.go#L\n328\nif_, ok := key.(ciliumNodeManagerQueueSyncedKey);ok {close(s.ciliumNodeManagerQueueSynced)returntrue}\nerr := syncHandler(key.(string))iferr ==nil{// If err is nil we can forget it from the queue,if it is not nil// the queue handler will retry to process thiskey until it succeeds.queue.Forget(key)returntrue}\nhttps://github.com/cilium/cilium/blob/c147bbd3211f0ef19eb13f4daab07e100e6b72d5/operator/pkg/ciliumendpointslic\ne/endpointslice.go#L203\n58Cilium security audit, 2022\nfuncsyncCESsInLocalCache(cesStore cache.Store, manager operations) {for_, obj :=rangecesStore.List() {ces :=obj.(*v2alpha1.CiliumEndpointSlice)// If CES is already cached locally, do nothing.\nhttps://github.com/cilium/cilium/blob/c147bbd3211f0ef19eb13f4daab07e100e6b72d5/operator/pkg/ciliumendpointslic\ne/endpointslice.go#L236\nfunc(c *CiliumEndpointSliceController)processNextWorkItem()bool{cKey, quit := c.queue.Get()ifquit {returnfalse}deferc.queue.Done(cKey)\nerr := c.syncCES(cKey.(string))c.handleErr(err, cKey)\nreturntrue}\nhttps://github.com/cilium/cilium/blob/c147bbd3211f0ef19eb13f4daab07e100e6b72d5/operator/pkg/ciliumendpointslic\ne/endpointslice.go#L278\nobj, exists, err := c.ciliumEndpointSliceStore.GetByKey(key)iferr ==nil&& exists {ces :=obj.(*v2alpha1.CiliumEndpointSlice)// Delete the CES, only if CEP count is zero inlocal copy of CES andapi-server copy of CES,// else Update the CESiflen(ces.Endpoints) ==0&& c.Manager.getCEPCountInCES(key)==0{iferr := c.reconciler.reconcileCESDelete(key);err !=nil{returnerr}}else{iferr := c.reconciler.reconcileCESUpdate(key);err !=nil{returnerr}}}\nhttps://github.com/cilium/cilium/blob/e3dfed84dc69990bbb68e9a181e984ec83dbe233/operator/pkg/gateway-api/contr\noller.go#L191-L222\nfunconlyStatusChanged()predicate.Predicate{option := cmpopts.IgnoreFields(metav1.Condition{},\"LastTransitionTime\")returnpredicate.Funcs{UpdateFunc:func(e event.UpdateEvent)bool{switche.ObjectOld.(type) {case*gatewayv1beta1.GatewayClass:o, _ := e.ObjectOld.(*gatewayv1beta1.GatewayClass)n, ok := e.ObjectNew.(*gatewayv1beta1.GatewayClass)if!ok {returnfalse}\n59Cilium security audit, 2022\nreturn!cmp.Equal(o.Status, n.Status, option)case*gatewayv1beta1.Gateway:o, _ := e.ObjectOld.(*gatewayv1beta1.Gateway)n, ok := e.ObjectNew.(*gatewayv1beta1.Gateway)if!ok {returnfalse}return!cmp.Equal(o.Status, n.Status, option)case*gatewayv1beta1.HTTPRoute:o, _ := e.ObjectOld.(*gatewayv1beta1.HTTPRoute)n, ok := e.ObjectNew.(*gatewayv1beta1.HTTPRoute)if!ok {returnfalse}return!cmp.Equal(o.Status, n.Status, option)default:returnfalse}},}}\nhttps://github.com/cilium/cilium/blob/d0a43aa05ee39b884\ufb009e87318e2a6aebd5ca98f/operator/pkg/gateway-api/httpro\nute.go#L44-L46\nfunc(rawObj client.Object) []string{hr, ok :=rawObj.(*gatewayv1beta1.HTTPRoute)if!ok {\nhttps://github.com/cilium/cilium/blob/d0a43aa05ee39b884\ufb009e87318e2a6aebd5ca98f/operator/pkg/gateway-api/httpro\nute.go#L70-L72\nfunc(rawObj client.Object) []string{hr :=rawObj.(*gatewayv1beta1.HTTPRoute)vargateways []string\nhttps://github.com/cilium/cilium/blob/8df3d1e320da86b75f07f65adcd185299a5b6d9c/operator/pkg/lbipam/lbipam.go#\nL398-L401\nfori :=0; i < poolRetryQueue.Len(); i++ {retryInt, _ := poolRetryQueue.Get()retry :=retryInt.(*retry)\nhttps://github.com/cilium/cilium/blob/6c98f152ad9e9d9882bc02840474dd39c04bd1e0/operator/watchers/cilium_endp\noint.go#L200-L204\nif!exists {returnnil,false,nil}cep :=item.(*cilium_api_v2.CiliumEndpoint)returncep, exists,nil\nhttps://github.com/cilium/cilium/blob/af61d36f5f20a7f3b07b8430a400073eb20c411c/operator/watchers/node_taint.go#\nL71\n60Cilium security audit, 2022\nsuccess := checkAndMarkNode(c, nodeGetter,key.(string), mno)\nhttps://github.com/cilium/cilium/blob/af61d36f5f20a7f3b07b8430a400073eb20c411c/operator/watchers/node_taint.go#\nL161\npodInterface, exists, err := ciliumPodsStore.GetByKey(key.(string))\nhttps://github.com/cilium/cilium/blob/af61d36f5f20a7f3b07b8430a400073eb20c411c/operator/watchers/node_taint.go#\nL170\npod :=podInterface.(*slim_corev1.Pod)\nhttps://github.com/cilium/cilium/blob/af61d36f5f20a7f3b07b8430a400073eb20c411c/operator/watchers/node_taint.go#\nL198\nciliumPod :=ciliumPodInterface.(*slim_corev1.Pod)\nhttps://github.com/cilium/cilium/blob/af61d36f5f20a7f3b07b8430a400073eb20c411c/operator/watchers/pod.go#L43\npod :=obj.(*slim_corev1.Pod)\nhttps://github.com/cilium/cilium/blob/d5227f1baed6eb56865dc08275e6560b\ufb00f27cce/pkg/datapath/ipcache/listener.go\n#L192\nk :=key.(*ipcacheMap.Key)\nhttps://github.com/cilium/cilium/blob/e4d68f84a7c957bc9c6b6fea3bfda3151f830629/pkg/datapath/loader/hash.go#L77\nstate, err := d.Hash.(encoding.BinaryMarshaler).MarshalBinary()\nhttps://github.com/cilium/cilium/blob/e4d68f84a7c957bc9c6b6fea3bfda3151f830629/pkg/datapath/loader/hash.go#L82\niferr :=newDatapathHash.(encoding.BinaryUnmarshaler).UnmarshalBinary(state);err !=nil{\nhttps://github.com/cilium/cilium/blob/be6d746ae29fc733bc3a58e2afcc79e77c35485b/pkg/endpoint/policy.go#L607\nregenResult :=result.(*EndpointRegenerationResult)\nhttps://github.com/cilium/cilium/blob/79c6f5725372b52c9877a9bde1249da039948649/pkg/envoy/server.go#L1778\nnetworkPolicy :=res.(*cilium.NetworkPolicy)\nhttps://github.com/cilium/cilium/blob/83f82482f9c831de712a14c9adc72caa0bda3dc3/pkg/envoy/xds/server.go#L274\nreq := recv.Interface().(*envoy_service_discovery.DiscoveryRequest)\nhttps://github.com/cilium/cilium/blob/83f82482f9c831de712a14c9adc72caa0bda3dc3/pkg/envoy/xds/server.go#L387\nresp := recv.Interface().(*VersionedResources)\n61Cilium security audit, 2022\nhttps://github.com/cilium/cilium/blob/e6ce5c17afc21448fa9e69a7a36eb41814532256/pkg/hubble/relay/queue/priority_\nqueue.go#L48\nresp := heap.Pop(&pq.h).(*observerpb.GetFlowsResponse)\nhttps://github.com/cilium/cilium/blob/e6ce5c17afc21448fa9e69a7a36eb41814532256/pkg/hubble/relay/queue/priority_\nqueue.go#L91\nresp :=x.(*observerpb.GetFlowsResponse)\nhttps://github.com/cilium/cilium/blob/69e4c6974891c161300889596f2029e489dded02/pkg/k8s/init.go#L102\ntypesNode :=nodeInterface.(*slim_corev1.Node)\nhttps://github.com/cilium/cilium/blob/09f72f77b460bfcb0eef09c4552026ec2e45fe65/pkg/k8s/resource/resource.go#L25\n4\nentry :=raw.(queueEntry)\nhttps://github.com/cilium/cilium/blob/183726c8da72d899ef9c205bb7f80d1a2577c099/pkg/maps/ctmap/ctmap.go#L285\nkey :=k.(CtKey)\nhttps://github.com/cilium/cilium/blob/183726c8da72d899ef9c205bb7f80d1a2577c099/pkg/maps/ctmap/ctmap.go#L289\nvalue :=v.(*CtEntry)\nhttps://github.com/cilium/cilium/blob/183726c8da72d899ef9c205bb7f80d1a2577c099/pkg/maps/ctmap/ctmap.go#L361\nentry :=value.(*CtEntry)\nhttps://github.com/cilium/cilium/blob/183726c8da72d899ef9c205bb7f80d1a2577c099/pkg/maps/ctmap/ctmap.go#L445\nentry :=value.(*CtEntry)\nhttps://github.com/cilium/cilium/blob/183726c8da72d899ef9c205bb7f80d1a2577c099/pkg/maps/ctmap/ctmap.go#L599\n-L600\nnatKey :=key.(nat.NatKey)natVal :=value.(nat.NatEntry)\nhttps://github.com/cilium/cilium/blob/183726c8da72d899ef9c205bb7f80d1a2577c099/pkg/maps/ctmap/utils.go#L37\nnatKey :=k.(*nat.NatKey6)\nhttps://github.com/cilium/cilium/blob/183726c8da72d899ef9c205bb7f80d1a2577c099/pkg/maps/ctmap/utils.go#L60\nnatVal :=v.(*nat.NatEntry4)\nhttps://github.com/cilium/cilium/blob/183726c8da72d899ef9c205bb7f80d1a2577c099/pkg/maps/ctmap/utils.go#L78-L7\n9\nnatKey :=k.(*nat.NatKey6)natVal :=v.(*nat.NatEntry6)\n62Cilium security audit, 2022\nhttps://github.com/cilium/cilium/blob/183726c8da72d899ef9c205bb7f80d1a2577c099/pkg/maps/ctmap/utils.go#L118\nnatKey :=k.(*nat.NatKey6)\nhttps://github.com/cilium/cilium/blob/58e4081c3c2a6e052d7c5e3443be33dd6ae5024b/pkg/maps/egressmap/policy.go\n#L176-L177\nkey :=k.(*EgressPolicyKey4)value :=v.(*EgressPolicyVal4)\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/pkg/maps/lbmap/ipv4.go#L242\nvHost := v.ToHost().(*RevNat4Value)\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/pkg/maps/lbmap/ipv4.go#L288\nkHost := k.ToHost().(*Service4Key)\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/pkg/maps/lbmap/ipv4.go#L342\nsHost := s.ToHost().(*Service4Value)\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/pkg/maps/lbmap/ipv4.go#L452\nvHost := v.ToHost().(*Backend4Value)\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/pkg/maps/lbmap/ipv4.go#L516\nvHost := v.ToHost().(*Backend4ValueV3)\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/pkg/maps/lbmap/ipv6.go#L109\nvHost := v.ToHost().(*RevNat6Value)\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/pkg/maps/lbmap/ipv6.go#L153\nkHost := k.ToHost().(*Service6Key)\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/pkg/maps/lbmap/ipv6.go#L207\nsHost := s.ToHost().(*Service6Value)\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/pkg/maps/lbmap/ipv6.go#L316\nvHost := v.ToHost().(*Backend6Value)\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/pkg/maps/lbmap/lbmap.go#L83\nsvcVal := svcKey.NewValue().(ServiceValue)\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/pkg/maps/lbmap/lbmap.go#L120\nzeroValue := svcKey.NewValue().(ServiceValue)\n63Cilium security audit, 2022\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/pkg/maps/lbmap/lbmap.go#L336\nmatchKey := key.DeepCopyMapKey().(*AffinityMatchKey).ToHost()\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/pkg/maps/lbmap/lbmap.go#L357\nk :=key.(SourceRangeKey).ToHost()\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/pkg/maps/lbmap/lbmap.go#L430\n-L438\nparseBackendEntries :=func(key bpf.MapKey, valuebpf.MapValue) {backendKey :=key.(BackendKey)backendValue := value.DeepCopyMapValue().(BackendValue).ToHost()backendValueMap[backendKey.GetID()] = backendValue}\nparseSVCEntries :=func(key bpf.MapKey, value bpf.MapValue){svcKey := key.DeepCopyMapKey().(ServiceKey).ToHost()svcValue := value.DeepCopyMapValue().(ServiceValue).ToHost()\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/pkg/maps/lbmap/lbmap.go#L514\n-L515\nbackendKey :=key.(BackendKey)backendValue := value.DeepCopyMapValue().(BackendValue).ToHost()\nhttps://github.com/cilium/cilium/blob/c6e53ea42bccbe8507e7df0f49319a2a853c054e/pkg/maps/lbmap/lbmap.go#L564\nzeroValue := fe.NewValue().(ServiceValue)\nhttps://github.com/cilium/cilium/blob/d5227f1baed6eb56865dc08275e6560b\ufb00f27cce/pkg/maps/lbmap/source_range.g\no#L52\nkHost := k.ToHost().(*SourceRangeKey4)\nhttps://github.com/cilium/cilium/blob/d5227f1baed6eb56865dc08275e6560b\ufb00f27cce/pkg/maps/lbmap/source_range.g\no#L96\nkHost := k.ToHost().(*SourceRangeKey6)\nhttps://github.com/cilium/cilium/blob/314ca7bae\ufb004f568\ufb00c0bad95124e40665b1f88c/pkg/maps/metricsmap/metricsma\np.go#L90-L91\nkey :=k.(*Key)values :=v.(*Values)\nhttps://github.com/cilium/cilium/blob/d5227f1baed6eb56865dc08275e6560b\ufb00f27cce/pkg/maps/nat/nat.go#L131-L138\ncb :=func(k bpf.MapKey, v bpf.MapValue) {key :=k.(NatKey)if!key.ToHost().Dump(&sb,false) {return}\n64Cilium security audit, 2022\nval :=v.(NatEntry)sb.WriteString(val.ToHost().Dump(key, nsecStart))}\nhttps://github.com/cilium/cilium/blob/d1d8e7a35b35d3420a33251767ae2696d664da53/pkg/maps/policymap/policyma\np.go#L375-L381\ncb :=func(key bpf.MapKey, value bpf.MapValue) {eDump := PolicyEntryDump{Key: *key.DeepCopyMapKey().(*PolicyKey),PolicyEntry: *value.DeepCopyMapValue().(*PolicyEntry),}entries =append(entries, eDump)}\nhttps://github.com/cilium/cilium/blob/314ca7bae\ufb004f568\ufb00c0bad95124e40665b1f88c/pkg/maps/recorder/recorder.go#L6\n0-L65\ncb :=func(k bpf.MapKey, v bpf.MapValue) {key :=k.(RecorderKey)key.ToHost().Dump(&sb)val :=v.(RecorderEntry)val.Dump(&sb)}\nhttps://github.com/cilium/cilium/blob/58e4081c3c2a6e052d7c5e3443be33dd6ae5024b/pkg/maps/srv6map/policy.go#L\n158-L167\nfunc(k, vinterface{}) {key4 :=k.(*PolicyKey4)key := PolicyKey{VRFID: key4.VRFID,DestCIDR: key4.getDestCIDR(),}value :=v.(*PolicyValue)\ncb(&key, value)})\nhttps://github.com/cilium/cilium/blob/58e4081c3c2a6e052d7c5e3443be33dd6ae5024b/pkg/maps/srv6map/policy.go#L\n174-L183\nfunc(k, vinterface{}) {key6 :=k.(*PolicyKey6)key := PolicyKey{VRFID: key6.VRFID,DestCIDR: key6.getDestCIDR(),}value :=v.(*PolicyValue)\ncb(&key, value)})\n65Cilium security audit, 2022\nhttps://github.com/cilium/cilium/blob/9c07b75282546500e26da55c46b7cf9c110205f0/pkg/maps/srv6map/sid.go#L96-L\n97\nkey :=k.(*SIDKey)value :=v.(*SIDValue)\nhttps://github.com/cilium/cilium/blob/fe9baa95eadc9ab678af619063ba443a4abcafbd/pkg/maps/srv6map/state.go#L92\n-L103\nfunc(k, vinterface{}) {key4 :=k.(*StateKey4)srcIP := key4.InnerSrc.IP()dstIP := key4.InnerDst.IP()key := StateKey{InnerSrc: &srcIP,InnerDst: &dstIP,}value :=v.(*StateValue)\ncb(&key, value)})\nhttps://github.com/cilium/cilium/blob/fe9baa95eadc9ab678af619063ba443a4abcafbd/pkg/maps/srv6map/state.go#L11\n0-L121\nfunc(k, vinterface{}) {key6 :=k.(*StateKey6)srcIP := key6.InnerSrc.IP()dstIP := key6.InnerDst.IP()key := StateKey{InnerSrc: &srcIP,InnerDst: &dstIP,}value :=v.(*StateValue)\ncb(&key, value)})\nhttps://github.com/cilium/cilium/blob/58e4081c3c2a6e052d7c5e3443be33dd6ae5024b/pkg/maps/srv6map/vrf.go#L158\n-L168\nfunc(k, vinterface{}) {key4 :=k.(*VRFKey4)srcIP := key4.SourceIP.IP()key := VRFKey{SourceIP: &srcIP,DestCIDR: key4.getDestCIDR(),}value :=v.(*VRFValue)\ncb(&key, value)})\nhttps://github.com/cilium/cilium/blob/58e4081c3c2a6e052d7c5e3443be33dd6ae5024b/pkg/maps/srv6map/vrf.go#L175\n-L185\n66Cilium security audit, 2022\nfunc(k, vinterface{}) {key6 :=k.(*VRFKey6)srcIP := key6.SourceIP.IP()key := VRFKey{SourceIP: &srcIP,DestCIDR: key6.getDestCIDR(),}value :=v.(*VRFValue)\ncb(&key, value)})\nhttps://github.com/cilium/cilium/blob/da9d6a0167e1cede54480dbe832ef0ef5dca3aa8/pkg/nodediscovery/nodediscove\nry.go#L456\ntypesNode :=nodeInterface.(*k8sTypes.Node)\n67Cilium security audit, 2022\n20: Ill-defined contexts\nOverall severity:\nInformational\nID:\nADA-CIL-20\nLocation:\nSeveral packages\nDescription\nAt the time of the audit, Cilium has 149 cases of ill-defined contexts -context.TODO()\n. To\nreproduce:\ngit clone https://github.com/cilium/cilium --depth=1cd ciliumrm -r testrm -r vendorgrep -r \u201ccontext\\.TODO\u201d --exclude=*_test.go\nThe Golang docs states aboutcontext.TODO()\n:\n\u201c\nTODO returns a non-nil, empty Context. Code should\nuse context.TODO when it's unclear which\nContext to use or it is not yet available (because the surrounding function has not yet been extended\nto accept a Context parameter).\n\u201d\nAs such, ill-defined contexts should be avoided in Ciliums production code.\nRecommendation\nA best e\ufb00ort of using well-defined contexts over time.\n68Cilium security audit, 2022\n21: Use of deprecated TLS version\nOverall severity:\nInformational\nID:\nADA-CIL-21\nLocation:pkg/crypto/certloader\nCWE\n\u25cf\nCWE-326: Inadequate Encryption Strength\n\u25cf\nCWE-327: Use of a Broken or Risky Cryptographic Algorithm\n\u25cf\nCWE-757: Selection of Less-Secure Algorithm During \nNegotiation ('Algorithm Downgrade')\nFix\nhttps://github.com/cilium/cilium/commit/ca890a4938f765be78db19ac77916e \n\ufb001be66a3f\nDescription\nBy default acrypto/tls.Config\nsets the minimum accepted\nTLS version to 1.0 when acting as a\nserver. From the Golang docs oncrypto/tls.Config\n:\n\u201c\n// By default, TLS 1.2 is currently used as the minimum\nwhen acting as a\n// client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum\n// supported by this package, both as a client and as a server.\n\u201d\nThis is an issue in case a minimum TLS version is not specified in the Config. TLS 1.0 and TLS 1.1 are\nformally deprecated and a number of known attacks are known to exploit weaknesses of the\nprotocols. For example, TLS 1.0 and TLS 1.0 rely on MD5 and SHA-1 which makes the protocols\nvulnerable to downgrade attacks. Authentication of handshakes is done based on SHA-1 which\nincreases the chance for an attacker to carry out a MITM attack by impersonating a server.\nhttps://github.com/cilium/cilium/blob/314ca7bae\ufb004f568\ufb00c0bad95124e40665b1f88c/pkg/crypto/c\nertloader/server.go#L102\nfunc(c *WatchedServerConfig)ServerConfig(base *tls.Config)*tls.Config{// We return a tls.Config having only the GetConfigForClientmember set.// When a client initialize a TLS handshake, thisfunction will be called// and the tls.Config returned by GetConfigForClientwill be used. This// mechanism allow us to reload the certificatestransparently between two// clients connections without having to restartthe server.// See also the discussion at https://github.com/golang/go/issues/16066.return&tls.Config{GetConfigForClient:func(_ *tls.ClientHelloInfo)(*tls.Config, error) {keypair, caCertPool := c.KeypairAndCACertPool()tlsConfig := base.Clone()tlsConfig.Certificates = []tls.Certificate{*keypair}ifc.IsMutualTLS() {// We've been configured to serve mTLS, so setuptheClientCAs// accordingly.tlsConfig.ClientCAs = caCertPool\n69Cilium security audit, 2022\n// The caller may have its own desire about the handshake// ClientAuthType. We honor it unless its tls.NoClientCert(the// default zero value) as we are configured toserve mTLS.iftlsConfig.ClientAuth == tls.NoClientCert {tlsConfig.ClientAuth =tls.RequireAndVerifyClientCert}}c.log.WithField(\"keypair-sn\", keypairId(keypair)).Debugf(\"Server tls handshake\")returntlsConfig,nil},}}\nRecommendations\nSpecify the minimum accepted TLS version in thecrypto/tls.Config\n.\nThe Cilium maintainers\ntriaged this issue and found\nthat the existing users of this libr ary code\nensur ed a newer TLS v ersion was used. This included Hubble clients and ser vers. The libr ary\ncode itself did not pr eviously enfor ce a new enough TLS v ersion.\n70Cilium security audit, 2022\n22: Deprecated function calls\nOverall severity:\nLow\nID:\nADA-CIL-22\nLocation:\nSeveral packages\nCWE:\n\u25cf\nCWE-477: Use of Obsolete Function\nDescription\nDeprecated 3rd-party APIs may be abandoned to a degree where patches to known security issues\nare not applied. Cilium makes calls to deprecated APIs in several places throughout the codebase.\nWe recommend creating a strategy to replace deprecated APIs over time. It could be shared in a\npublic Github issue to get support from the community.\nAt commit398cf5e051c49a46941d1efedf9659740d80f52c\n,\nthese are the uses of deprecated APIs\nthat need addressing:\nLocation\nDeprecated API call\napi/v1/health/server/server.go:316:3httpsServer.TLSConfig.BuildNameToCertificate\napi/v1/operator/server/server.go:317:3httpsServer.TLSConfig.BuildNameToCertificate\napi/v1/server/server.go:316:3httpsServer.TLSConfig.BuildNameToCertificate\ndaemon/cmd/status.go:256:29strings.Title\ndaemon/cmd/status.go:266:37strings.Title\noperator/metrics/metrics.go:139:24prometheus.NewProcessCollector\npkg/aws/ec2/ec2.go:79:25aws.EndpointResolverFunc\npkg/envoy/accesslog_server.go:167:14pblog.Method\npkg/envoy/accesslog_server.go:168:18pblog.Status\npkg/envoy/accesslog_server.go:169:23pblog.Scheme\npkg/envoy/accesslog_server.go:169:37pblog.Host\npkg/envoy/accesslog_server.go:169:49pblog.Path\npkg/envoy/accesslog_server.go:170:26pblog.HttpProtocol\npkg/envoy/accesslog_server.go:171:32pblog.Headers\n71Cilium security audit, 2022\npkg/envoy/sort.go:221:8m1.GetExactMatch\npkg/envoy/sort.go:222:8m2.GetExactMatch\npkg/envoy/sort.go:230:10m1.GetSafeRegexMatch\npkg/envoy/sort.go:231:10m2.GetSafeRegexMatch\npkg/envoy/sort.go:275:7m1.GetPrefixMatch\npkg/envoy/sort.go:276:7m2.GetPrefixMatch\npkg/envoy/sort.go:284:7m1.GetSuffixMatch\npkg/envoy/sort.go:285:7m2.GetSuffixMatch\npkg/health/client/client.go:59:3tr.Dial\npkg/health/client/client.go:64:3tr.Dial\npkg/hubble/metrics/drop/handler.go:56:62flow.GetDropReason\npkg/hubble/parser/seven/parser.go:125:2decoded.DropReason\npkg/hubble/parser/seven/parser.go:137:2decoded.Reply\npkg/hubble/parser/seven/parser.go:144:2decoded.Summary\npkg/hubble/parser/sock/parser.go:118:2decoded.Summary\npkg/hubble/parser/threefour/parser.go:193:2decoded.DropReason\npkg/hubble/parser/threefour/parser.go:194:41decoded.DropReason\npkg/hubble/parser/threefour/parser.go:205:2decoded.Reply\npkg/hubble/parser/threefour/parser.go:214:2decoded.Summary\npkg/hubble/peer/types/client.go:56:45grpc.WithInsecure\npkg/hubble/relay/pool/client.go:53:23grpc.WithInsecure\npkg/hubble/relay/pool/option.go:29:4grpc.WithInsecure\npkg/k8s/informer/informer.go:86:10cache.NewDeltaFIFO\npkg/k8s/slim/k8s/apis/labels/selector.go:270:32sets.String\npkg/k8s/slim/k8s/apis/labels/selector.go:271:9sets.String\npkg/k8s/slim/k8s/apis/labels/selector.go:689:13sets.String\npkg/k8s/slim/k8s/apis/labels/selector.go:755:33sets.String\npkg/k8s/slim/k8s/apis/labels/selector.go:781:42sets.String\npkg/k8s/slim/k8s/apis/labels/selector.go:817:37sets.String\nproxylib/npds/client.go:137:35grpc.WithInsecure\n72" - } -] \ No newline at end of file