Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate random kernel interface names #1590

Merged
merged 8 commits into from
Mar 21, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions pkg/networkservice/common/mechanisms/kernel/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
//
// Copyright (c) 2021 Doc.ai and/or its affiliates.
//
// Copyright (c) 2024 Cisco and/or its affiliates.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
Expand All @@ -22,6 +24,7 @@
"context"

"github.com/golang/protobuf/ptypes/empty"
"github.com/pkg/errors"
"google.golang.org/grpc"

"github.com/networkservicemesh/api/pkg/api/networkservice"
Expand All @@ -46,12 +49,20 @@
}

func (k *kernelMechanismClient) Request(ctx context.Context, request *networkservice.NetworkServiceRequest, opts ...grpc.CallOption) (*networkservice.Connection, error) {
if !k.updateMechanismPreferences(request) {
updated, err := k.updateMechanismPreferences(request)
NikitaSkrynnik marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return nil, errors.Wrap(err, "Failed to update mechanism preferences")
}

Check warning on line 55 in pkg/networkservice/common/mechanisms/kernel/client.go

View check run for this annotation

Codecov / codecov/patch

pkg/networkservice/common/mechanisms/kernel/client.go#L54-L55

Added lines #L54 - L55 were not covered by tests
if !updated {
mechanism := kernelmech.ToMechanism(kernelmech.New(netNSURL))
if k.interfaceName != "" {
mechanism.SetInterfaceName(k.interfaceName)
} else {
mechanism.SetInterfaceName(getNameFromConnection(request.GetConnection()))
ifname, err := generateInterfaceName()
if err != nil {
return nil, errors.Wrap(err, "Failed to generate kernel interface name")
}

Check warning on line 64 in pkg/networkservice/common/mechanisms/kernel/client.go

View check run for this annotation

Codecov / codecov/patch

pkg/networkservice/common/mechanisms/kernel/client.go#L63-L64

Added lines #L63 - L64 were not covered by tests
mechanism.SetInterfaceName(ifname)
}
request.MechanismPreferences = append(request.GetMechanismPreferences(), mechanism.Mechanism)
}
Expand All @@ -63,7 +74,7 @@
}

// updateMechanismPreferences returns true if MechanismPreferences has updated
NikitaSkrynnik marked this conversation as resolved.
Show resolved Hide resolved
func (k *kernelMechanismClient) updateMechanismPreferences(request *networkservice.NetworkServiceRequest) bool {
func (k *kernelMechanismClient) updateMechanismPreferences(request *networkservice.NetworkServiceRequest) (bool, error) {
var updated = false

for _, m := range request.GetRequestMechanismPreferences() {
Expand All @@ -72,7 +83,11 @@
if k.interfaceName != "" {
mechanism.SetInterfaceName(k.interfaceName)
} else {
mechanism.SetInterfaceName(getNameFromConnection(request.GetConnection()))
ifname, err := generateInterfaceName()
if err != nil {
return false, errors.Wrap(err, "Failed to generate kernel interface name")
}

Check warning on line 89 in pkg/networkservice/common/mechanisms/kernel/client.go

View check run for this annotation

Codecov / codecov/patch

pkg/networkservice/common/mechanisms/kernel/client.go#L88-L89

Added lines #L88 - L89 were not covered by tests
mechanism.SetInterfaceName(ifname)
}
}
mechanism.SetNetNSURL(netNSURL)
Expand All @@ -81,5 +96,5 @@
}
}

return updated
return updated, nil
}
21 changes: 21 additions & 0 deletions pkg/networkservice/common/mechanisms/kernel/client_test.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Copyright (c) 2021 Doc.ai and/or its affiliates.
//
// Copyright (c) 2024 Cisco and/or its affiliates.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
Expand All @@ -19,6 +21,7 @@ package kernel_test
import (
"context"
"net/url"
"strings"
"testing"

"github.com/stretchr/testify/require"
Expand All @@ -27,6 +30,8 @@ import (
kernelmech "github.com/networkservicemesh/api/pkg/api/networkservice/mechanisms/kernel"

"github.com/networkservicemesh/sdk/pkg/networkservice/common/mechanisms/kernel"

"github.com/networkservicemesh/sdk/pkg/tools/nanoid"
)

var netNSURL = (&url.URL{Scheme: "file", Path: "/proc/thread-self/ns/net"}).String()
Expand Down Expand Up @@ -72,3 +77,19 @@ func TestKernelMechanismClient_ShouldSetValidNetNSURL(t *testing.T) {
require.NoError(t, err)
require.Equal(t, netNSURL, req.MechanismPreferences[0].Parameters[kernelmech.NetNSURL])
}

func TestKernelMechanismClient_ShouldSetRandomInteraceName(t *testing.T) {
c := kernel.NewClient()
req := &networkservice.NetworkServiceRequest{}

_, err := c.Request(context.Background(), req)
require.NoError(t, err)

ifname := req.MechanismPreferences[0].Parameters[kernelmech.InterfaceNameKey]

require.Len(t, ifname, kernelmech.LinuxIfMaxLength)
require.True(t, strings.HasPrefix(ifname, "nsm"))
for i := 0; i < kernelmech.LinuxIfMaxLength; i++ {
require.Contains(t, nanoid.DefaultAlphabet, string(ifname[i]))
}
}
9 changes: 8 additions & 1 deletion pkg/networkservice/common/mechanisms/kernel/server.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Copyright (c) 2020-2021 Doc.ai and/or its affiliates.
//
// Copyright (c) 2024 Cisco and/or its affiliates.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
Expand All @@ -21,6 +23,7 @@
"context"

"github.com/golang/protobuf/ptypes/empty"
"github.com/pkg/errors"

"github.com/networkservicemesh/api/pkg/api/networkservice"
kernelmech "github.com/networkservicemesh/api/pkg/api/networkservice/mechanisms/kernel"
Expand Down Expand Up @@ -49,7 +52,11 @@
if m.interfaceName != "" {
mechanism.SetInterfaceName(m.interfaceName)
} else {
mechanism.SetInterfaceName(getNameFromConnection(request.GetConnection()))
ifname, err := generateInterfaceName()
if err != nil {
return nil, errors.Wrap(err, "Failed to generate kernel interface name")
}
mechanism.SetInterfaceName(ifname)

Check warning on line 59 in pkg/networkservice/common/mechanisms/kernel/server.go

View check run for this annotation

Codecov / codecov/patch

pkg/networkservice/common/mechanisms/kernel/server.go#L55-L59

Added lines #L55 - L59 were not covered by tests
}
}
return next.Server(ctx).Request(ctx, request)
Expand Down
26 changes: 17 additions & 9 deletions pkg/networkservice/common/mechanisms/kernel/utils.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Copyright (c) 2021 Doc.ai and/or its affiliates.
//
// Copyright (c) 2024 Cisco and/or its affiliates.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
Expand All @@ -20,21 +22,27 @@
"fmt"
"net/url"

"github.com/networkservicemesh/api/pkg/api/networkservice"
kernelmech "github.com/networkservicemesh/api/pkg/api/networkservice/mechanisms/kernel"

"github.com/networkservicemesh/sdk/pkg/tools/nanoid"
)

const (
ifPrefix = "nsm"
)

var netNSURL = (&url.URL{Scheme: "file", Path: "/proc/thread-self/ns/net"}).String()

// getNameFromConnection - returns a name computed from networkservice.Connection 'conn'
func getNameFromConnection(conn *networkservice.Connection) string {
ns := conn.GetNetworkService()
nsMaxLength := kernelmech.LinuxIfMaxLength - 5
if len(ns) > nsMaxLength {
ns = ns[:nsMaxLength]
// generateInterfaceName - returns a random interface name with "nsm" prefix
func generateInterfaceName() (string, error) {
NikitaSkrynnik marked this conversation as resolved.
Show resolved Hide resolved
ifIDLen := kernelmech.LinuxIfMaxLength - len(ifPrefix)
id, err := nanoid.RandomString(ifIDLen)
if err != nil {
return "", err

Check warning on line 41 in pkg/networkservice/common/mechanisms/kernel/utils.go

View check run for this annotation

Codecov / codecov/patch

pkg/networkservice/common/mechanisms/kernel/utils.go#L41

Added line #L41 was not covered by tests
}
name := fmt.Sprintf("%s-%s", ns, conn.GetId())
return limitName(name)
name := fmt.Sprintf("%s%s", ifPrefix, id)

return limitName(name), nil
}

func limitName(name string) string {
Expand Down
12 changes: 9 additions & 3 deletions pkg/networkservice/common/mechanismtranslation/client_test.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Copyright (c) 2020-2021 Doc.ai and/or its affiliates.
//
// Copyright (c) 2024 Cisco and/or its affiliates.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -41,13 +43,17 @@ import (
"github.com/networkservicemesh/sdk/pkg/networkservice/utils/metadata"
)

const (
clientIfName = "nsm1"
)

func kernelMechanism() *networkservice.Mechanism {
request := &networkservice.NetworkServiceRequest{
Connection: &networkservice.Connection{
Id: "id",
},
}
_, _ = kernel.NewClient().Request(context.Background(), request)
_, _ = kernel.NewClient(kernel.WithInterfaceName(clientIfName)).Request(context.Background(), request)
return request.MechanismPreferences[0]
}

Expand All @@ -58,7 +64,7 @@ func TestMechanismTranslationClient(t *testing.T) {
metadata.NewClient(),
mechanismtranslation.NewClient(),
capture,
kernel.NewClient(),
kernel.NewClient(kernel.WithInterfaceName(clientIfName)),
adapters.NewServerToClient(
mechanisms.NewServer(map[string]networkservice.NetworkServiceServer{
kernelmech.MECHANISM: null.NewServer(),
Expand Down Expand Up @@ -130,7 +136,7 @@ func TestMechanismTranslationClient_CloseOnError(t *testing.T) {
}
count++
}),
kernel.NewClient(),
kernel.NewClient(kernel.WithInterfaceName(clientIfName)),
adapters.NewServerToClient(
mechanisms.NewServer(map[string]networkservice.NetworkServiceServer{
kernelmech.MECHANISM: null.NewServer(),
Expand Down
88 changes: 88 additions & 0 deletions pkg/tools/nanoid/generator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Copyright (c) 2024 Cisco and/or its affiliates.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package nanoid is a tiny, unique string ID generator
package nanoid

import (
"crypto/rand"
"math"
"math/bits"
)

const (
// DefaultAlphabet is the default alphabet for the generator which can be used to generate kernel interface names
DefaultAlphabet = "!\"#$&'()*+,-.012456789;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
)

type generatorOpts struct {
alphabet string
}

// Option represents options for the string generator
type Option func(o *generatorOpts)

// WithAlphabet sets a custom alphabet for the generator
func WithAlphabet(alphabet string) Option {
return func(o *generatorOpts) {
o.alphabet = alphabet
}
}

func generateRandomBuffer(step int) ([]byte, error) {
buffer := make([]byte, step)
if _, err := rand.Read(buffer); err != nil {
denis-tingaikin marked this conversation as resolved.
Show resolved Hide resolved
return nil, err
}

Check warning on line 49 in pkg/tools/nanoid/generator.go

View check run for this annotation

Codecov / codecov/patch

pkg/tools/nanoid/generator.go#L48-L49

Added lines #L48 - L49 were not covered by tests
return buffer, nil
}

// RandomString generates a random string based on size.
NikitaSkrynnik marked this conversation as resolved.
Show resolved Hide resolved
// Original JavaScript implementation: https://github.com/ai/nanoid/blob/main/README.md
func RandomString(size int, opt ...Option) (string, error) {
opts := &generatorOpts{
alphabet: DefaultAlphabet,
}

for _, o := range opt {
o(opts)
}

mask := 2<<uint32(31-bits.LeadingZeros32(uint32(len(opts.alphabet)-1|1))) - 1
step := int(math.Ceil(1.6 * float64(mask*size) / float64(len(opts.alphabet))))

id := make([]byte, size)

for {
randomBuffer, err := generateRandomBuffer(step)
if err != nil {
return "", err
}

Check warning on line 73 in pkg/tools/nanoid/generator.go

View check run for this annotation

Codecov / codecov/patch

pkg/tools/nanoid/generator.go#L72-L73

Added lines #L72 - L73 were not covered by tests

j := 0
for i := 0; i < step; i++ {
currentIndex := int(randomBuffer[i]) & mask

if currentIndex < len(opts.alphabet) {
id[j] = opts.alphabet[currentIndex]
j++
if j == size {
return string(id), nil
}
}
}
}
}
Loading
Loading