github.com/cilium/cilium@v1.16.2/pkg/maps/encrypt/encrypt.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright Authors of Cilium 3 4 package encrypt 5 6 import ( 7 "fmt" 8 "sync" 9 10 "github.com/cilium/cilium/pkg/bpf" 11 "github.com/cilium/cilium/pkg/ebpf" 12 "github.com/cilium/cilium/pkg/option" 13 ) 14 15 // EncryptKey is the context ID for the encryption session 16 type EncryptKey struct { 17 key uint32 `align:"ctx"` 18 } 19 20 // EncryptValue is ID assigned to the keys 21 type EncryptValue struct { 22 encryptKeyID uint8 23 } 24 25 // String pretty print the EncryptKey 26 func (k EncryptKey) String() string { 27 return fmt.Sprintf("%d", k.key) 28 } 29 30 func (k EncryptKey) New() bpf.MapKey { return &EncryptKey{} } 31 32 // String pretty print the encryption key index. 33 func (v EncryptValue) String() string { 34 return fmt.Sprintf("%d", v.encryptKeyID) 35 } 36 37 func (v EncryptValue) New() bpf.MapValue { return &EncryptValue{} } 38 39 func newEncryptKey(key uint32) *EncryptKey { 40 return &EncryptKey{ 41 key: key, 42 } 43 } 44 45 const ( 46 // MapName name of map used to pin map for datapath 47 MapName = "cilium_encrypt_state" 48 49 // MaxEntries represents the maximum number of current encryption contexts 50 MaxEntries = 1 51 ) 52 53 var ( 54 once sync.Once 55 encryptMap *bpf.Map 56 ) 57 58 // NewMap will construct a bpf.Map that is not open or created yet. 59 func NewMap(MapName string) *bpf.Map { 60 return bpf.NewMap(MapName, 61 ebpf.Array, 62 &EncryptKey{}, 63 &EncryptValue{}, 64 MaxEntries, 65 0, 66 ) 67 } 68 69 // MapCreate will create an encrypt map that is ready for use. 70 func MapCreate() error { 71 once.Do(func() { 72 encryptMap = NewMap(MapName).WithCache(). 73 WithEvents(option.Config.GetEventBufferConfig(MapName)) 74 }) 75 76 return encryptMap.OpenOrCreate() 77 } 78 79 // MapUpdateContext updates the encrypt state with ctxID to use the new keyID 80 func MapUpdateContext(ctxID uint32, keyID uint8) error { 81 k := newEncryptKey(ctxID) 82 v := &EncryptValue{ 83 encryptKeyID: keyID, 84 } 85 return encryptMap.Update(k, v) 86 } 87 88 // MapUpdateContextWithMap updates the encrypt state with ctxID to use the new keyID 89 // with the map as its argument. 90 // 91 // This is primarily used in tests. 92 func MapUpdateContextWithMap(m *bpf.Map, ctxID uint32, keyID uint8) error { 93 k := newEncryptKey(ctxID) 94 v := &EncryptValue{ 95 encryptKeyID: keyID, 96 } 97 return m.Update(k, v) 98 }