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 7 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
65 changes: 44 additions & 21 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,39 +24,40 @@
"context"

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

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

"github.com/networkservicemesh/sdk/pkg/networkservice/core/next"
"github.com/networkservicemesh/sdk/pkg/tools/nanoid"
)

type kernelMechanismClient struct {
interfaceName string
interfaceName string
interfaceNameGenerator func(int) (string, error)
}

// NewClient - returns client that sets kernel preferred mechanism
func NewClient(opts ...Option) networkservice.NetworkServiceClient {
o := &options{}
o := &options{
interfaceNameGenerator: nanoid.New(),
}
for _, opt := range opts {
opt(o)
}
return &kernelMechanismClient{
interfaceName: o.interfaceName,
interfaceName: o.interfaceName,
interfaceNameGenerator: o.interfaceNameGenerator,
}
}

func (k *kernelMechanismClient) Request(ctx context.Context, request *networkservice.NetworkServiceRequest, opts ...grpc.CallOption) (*networkservice.Connection, error) {
if !k.updateMechanismPreferences(request) {
mechanism := kernelmech.ToMechanism(kernelmech.New(netNSURL))
if k.interfaceName != "" {
mechanism.SetInterfaceName(k.interfaceName)
} else {
mechanism.SetInterfaceName(getNameFromConnection(request.GetConnection()))
}
request.MechanismPreferences = append(request.GetMechanismPreferences(), mechanism.Mechanism)
if err := k.manageMechanismPreferences(request); err != nil {
return nil, errors.Wrap(err, "Failed to update mechanism preferences")
}

return next.Client(ctx).Request(ctx, request, opts...)
}

Expand All @@ -63,23 +66,43 @@
}

// 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) manageMechanismPreferences(request *networkservice.NetworkServiceRequest) error {
var updated = false

for _, m := range request.GetRequestMechanismPreferences() {
if mechanism := kernelmech.ToMechanism(m); mechanism != nil {
if mechanism.GetInterfaceName() == "" {
if k.interfaceName != "" {
mechanism.SetInterfaceName(k.interfaceName)
} else {
mechanism.SetInterfaceName(getNameFromConnection(request.GetConnection()))
}
if err := k.updateMechanism(mechanism); err != nil {
return err

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

View check run for this annotation

Codecov / codecov/patch

pkg/networkservice/common/mechanisms/kernel/client.go#L74

Added line #L74 was not covered by tests
}
mechanism.SetNetNSURL(netNSURL)

updated = true
}
}

return updated
if updated {
return nil
}

mechanism := kernelmech.ToMechanism(kernelmech.New(netNSURL))
if err := k.updateMechanism(mechanism); err != nil {
return err
}

request.MechanismPreferences = append(request.GetMechanismPreferences(), mechanism.Mechanism)
return nil
}

func (k *kernelMechanismClient) updateMechanism(mechanism *kernelmech.Mechanism) error {
if mechanism.GetInterfaceName() == "" {
if k.interfaceName != "" {
mechanism.SetInterfaceName(k.interfaceName)
} else {
ifname, err := generateInterfaceName(k.interfaceNameGenerator)
if err != nil {
return errors.Wrap(err, "Failed to generate kernel interface name")
}
mechanism.SetInterfaceName(ifname)
}
}

return nil
}
37 changes: 37 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,14 +21,18 @@ package kernel_test
import (
"context"
"net/url"
"strings"
"testing"

"github.com/pkg/errors"
"github.com/stretchr/testify/require"

"github.com/networkservicemesh/api/pkg/api/networkservice"
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 +78,34 @@ 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]))
}
}

type brokenByteGenerator struct {
}

func (g *brokenByteGenerator) Read(buffer []byte) (int, error) {
return 0, errors.New("failed to generate bytes")
}

func TestKernelMechanismClient_FailedToGenerateRandomName(t *testing.T) {
c := kernel.NewClient(kernel.WithInterfaceNameGenerator(nanoid.New(nanoid.WithRandomByteGenerator(&brokenByteGenerator{}))))
req := &networkservice.NetworkServiceRequest{}

_, err := c.Request(context.Background(), req)
require.Error(t, err)
}
12 changes: 11 additions & 1 deletion pkg/networkservice/common/mechanisms/kernel/option.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 @@ -17,7 +19,8 @@
package kernel

type options struct {
interfaceName string
interfaceName string
interfaceNameGenerator func(int) (string, error)
}

// Option is an option pattern for kernelMechanismClient/Server
Expand All @@ -29,3 +32,10 @@ func WithInterfaceName(interfaceName string) Option {
o.interfaceName = limitName(interfaceName)
}
}

// WithInterfaceNameGenerator sets a generator for generating random interface names
func WithInterfaceNameGenerator(generator func(int) (string, error)) Option {
return func(o *options) {
o.interfaceNameGenerator = generator
}
}
20 changes: 16 additions & 4 deletions 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,25 +23,31 @@
"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"

"github.com/networkservicemesh/sdk/pkg/networkservice/core/next"
"github.com/networkservicemesh/sdk/pkg/tools/nanoid"
)

type kernelMechanismServer struct {
interfaceName string
interfaceName string
interfaceNameGenerator func(int) (string, error)
}

// NewServer - creates a NetworkServiceServer that requests a kernel interface and populates the netns inode
func NewServer(opts ...Option) networkservice.NetworkServiceServer {
o := &options{}
o := &options{
interfaceNameGenerator: nanoid.New(),
}

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

View check run for this annotation

Codecov / codecov/patch

pkg/networkservice/common/mechanisms/kernel/server.go#L42-L44

Added lines #L42 - L44 were not covered by tests
for _, opt := range opts {
opt(o)
}
return &kernelMechanismServer{
interfaceName: o.interfaceName,
interfaceName: o.interfaceName,
interfaceNameGenerator: o.interfaceNameGenerator,

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

View check run for this annotation

Codecov / codecov/patch

pkg/networkservice/common/mechanisms/kernel/server.go#L49-L50

Added lines #L49 - L50 were not covered by tests
}
}

Expand All @@ -49,7 +57,11 @@
if m.interfaceName != "" {
mechanism.SetInterfaceName(m.interfaceName)
} else {
mechanism.SetInterfaceName(getNameFromConnection(request.GetConnection()))
ifname, err := generateInterfaceName(m.interfaceNameGenerator)
if err != nil {
return nil, errors.Wrap(err, "Failed to generate kernel interface name")
}
mechanism.SetInterfaceName(ifname)

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

View check run for this annotation

Codecov / codecov/patch

pkg/networkservice/common/mechanisms/kernel/server.go#L60-L64

Added lines #L60 - L64 were not covered by tests
}
}
return next.Server(ctx).Request(ctx, request)
Expand Down
86 changes: 86 additions & 0 deletions pkg/networkservice/common/mechanisms/kernel/server_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// 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 kernel_test

import (
"context"
"strings"
"testing"

"github.com/stretchr/testify/require"

"github.com/networkservicemesh/api/pkg/api/networkservice"
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"
)

func TestKernelMechanismServer_ShouldSetInterfaceName(t *testing.T) {
var expectedIfaceName string
for i := 0; i < kernelmech.LinuxIfMaxLength; i++ {
expectedIfaceName += "a"
}

c := kernel.NewClient(kernel.WithInterfaceName(expectedIfaceName + "long-suffix"))

req := &networkservice.NetworkServiceRequest{}
_, err := c.Request(context.Background(), req)
require.NoError(t, err)

require.Len(t, req.MechanismPreferences, 1)
require.Equal(t, expectedIfaceName, req.MechanismPreferences[0].Parameters[kernelmech.InterfaceNameKey])
}

func TestKernelMechanismServer_ShouldSetValidNetNSURL(t *testing.T) {
c := kernel.NewClient()

req := &networkservice.NetworkServiceRequest{
MechanismPreferences: []*networkservice.Mechanism{
kernelmech.New("invalid-url"),
},
}

_, err := c.Request(context.Background(), req)
require.NoError(t, err)
require.Equal(t, netNSURL, req.MechanismPreferences[0].Parameters[kernelmech.NetNSURL])
}

func TestKernelMechanismServer_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]))
}
}

func TestKernelMechanismServer_FailedToGenerateRandomName(t *testing.T) {
c := kernel.NewClient(kernel.WithInterfaceNameGenerator(nanoid.New(nanoid.WithRandomByteGenerator(&brokenByteGenerator{}))))
req := &networkservice.NetworkServiceRequest{}

_, err := c.Request(context.Background(), req)
require.Error(t, err)
}
25 changes: 16 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,26 @@ import (
"fmt"
"net/url"

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

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
// to achieve a 1% chance of name collision, you need to generate approximately 68 billon names
func generateInterfaceName(generator func(int) (string, error)) (string, error) {
ifIDLen := kernelmech.LinuxIfMaxLength - len(ifPrefix)
id, err := generator(ifIDLen)
if err != nil {
return "", err
}
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
Loading
Loading