-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add applyiptables4nattemplate chain element
Signed-off-by: Sergey Shlyanin <sergey.shlyanin@xored.com>
- Loading branch information
Sergey Shlyanin
committed
May 10, 2022
1 parent
396e655
commit 21c1649
Showing
4 changed files
with
247 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
123 changes: 123 additions & 0 deletions
123
pkg/kernel/networkservice/applyiptables4nattemplate/common.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
// Copyright (c) 2022 Xored Software Inc and others. | ||
// | ||
// 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. | ||
|
||
//go:build linux | ||
// +build linux | ||
|
||
package applyiptables4nattemplate | ||
|
||
import ( | ||
"bytes" | ||
"fmt" | ||
"log" | ||
"os" | ||
"strings" | ||
|
||
"github.com/edwarnicke/exechelper" | ||
"github.com/pkg/errors" | ||
) | ||
|
||
type applyIPTablesKey struct { | ||
} | ||
|
||
type iptableManagerImpl struct { | ||
} | ||
|
||
// IPTablesManager provides methods for iptables nat rules management | ||
type IPTablesManager interface { | ||
Get() (string, error) | ||
Restore(string) error | ||
Apply(string) error | ||
} | ||
|
||
func (m *iptableManagerImpl) Get() (string, error) { | ||
cmdStr := "iptables-save" | ||
buf := bytes.NewBuffer([]byte{}) | ||
err := exechelper.Run(cmdStr, | ||
exechelper.WithStdout(buf), | ||
exechelper.WithStderr(buf), | ||
) | ||
if err != nil { | ||
err = errors.Wrapf(err, "%s", buf.String()) | ||
return "", err | ||
} | ||
|
||
return buf.String(), nil | ||
} | ||
|
||
func (m *iptableManagerImpl) Apply(rulesTemplate string) error { | ||
rules := strings.Split(rulesTemplate, "\n") | ||
|
||
for _, rule := range rules { | ||
// Remove possible tabs from a multistring template | ||
rule = strings.Trim(rule, "\t ") | ||
arguments := strings.Split(rule, " ") | ||
log.Println(rule) | ||
|
||
cmdStr := "iptables -t nat" | ||
buf := bytes.NewBuffer([]byte{}) | ||
err := exechelper.Run(cmdStr, | ||
exechelper.WithArgs(arguments...), | ||
exechelper.WithStdout(buf), | ||
exechelper.WithStderr(buf), | ||
) | ||
if err != nil { | ||
err = errors.Wrapf(err, "%s", buf.String()) | ||
return err | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func (m *iptableManagerImpl) writeTmpRule(rules string) (string, error) { | ||
fo, err := os.CreateTemp("/tmp", "rules-*") | ||
if err != nil { | ||
return "", err | ||
} | ||
|
||
defer func() { _ = fo.Close() }() | ||
_, err = fo.WriteString(rules) | ||
if err != nil { | ||
return "", err | ||
} | ||
|
||
return fo.Name(), nil | ||
} | ||
|
||
func (m *iptableManagerImpl) Restore(rules string) error { | ||
// Save rules to a temp file | ||
tmpFile, err := m.writeTmpRule(rules) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
defer func() { _ = os.Remove(tmpFile) }() | ||
|
||
// Restore rules | ||
cmdStr := fmt.Sprintf("iptables-restore %s", tmpFile) | ||
buf := bytes.NewBuffer([]byte{}) | ||
err = exechelper.Run(cmdStr, | ||
exechelper.WithStdout(buf), | ||
exechelper.WithStderr(buf), | ||
) | ||
if err != nil { | ||
err = errors.Wrapf(err, "%s", buf.String()) | ||
return err | ||
} | ||
|
||
return nil | ||
} |
115 changes: 115 additions & 0 deletions
115
pkg/kernel/networkservice/applyiptables4nattemplate/server.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
// Copyright (c) 2022 Xored Software Inc and others. | ||
// | ||
// 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. | ||
|
||
//go:build linux | ||
// +build linux | ||
|
||
// Package applyiptables4nattemplate provides chain element for setup iptables nat rules | ||
package applyiptables4nattemplate | ||
|
||
import ( | ||
"context" | ||
|
||
"github.com/golang/protobuf/ptypes/empty" | ||
"github.com/pkg/errors" | ||
|
||
"github.com/networkservicemesh/api/pkg/api/networkservice" | ||
"github.com/networkservicemesh/api/pkg/api/networkservice/mechanisms/kernel" | ||
"github.com/networkservicemesh/sdk/pkg/networkservice/core/next" | ||
"github.com/networkservicemesh/sdk/pkg/networkservice/utils/metadata" | ||
) | ||
|
||
type iptablesServer struct { | ||
manager IPTablesManager | ||
} | ||
|
||
// Option is an option pattern for applyiptables4nattemplate chain elements | ||
type Option func(server *iptablesServer) | ||
|
||
// WithIPTablesManager provides an option to change IPTablesManager for a chain element | ||
func WithIPTablesManager(iptable IPTablesManager) Option { | ||
return func(server *iptablesServer) { | ||
server.manager = iptable | ||
} | ||
} | ||
|
||
// NewServer - returns a new networkservice.NetworkServiceServer that modify IPTables rules | ||
// by mechanism provided template on Request and rollbacks rules changes on Close | ||
func NewServer(options ...Option) networkservice.NetworkServiceServer { | ||
result := &iptablesServer{ | ||
manager: &iptableManagerImpl{}, | ||
} | ||
|
||
for _, option := range options { | ||
option(result) | ||
} | ||
|
||
return result | ||
} | ||
|
||
func (s *iptablesServer) Request(ctx context.Context, request *networkservice.NetworkServiceRequest) (*networkservice.Connection, error) { | ||
ctxMap := metadata.Map(ctx, metadata.IsClient(s)) | ||
_, rulesWasApplied := ctxMap.Load(applyIPTablesKey{}) | ||
|
||
conn, err := next.Server(ctx).Request(ctx, request) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
// Check refresh requests | ||
if !rulesWasApplied { | ||
mechanism := kernel.ToMechanism(request.GetConnection().GetMechanism()) | ||
if mechanism != nil && mechanism.GetIPTables4NatTemplate() != "" { | ||
rules, err := mechanism.EvaluateIPTables4NatTemplate(request.GetConnection()) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
initialRules, err := s.manager.Get() | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
ctxMap.Store(applyIPTablesKey{}, initialRules) | ||
|
||
err = s.manager.Apply(rules) | ||
if err != nil { | ||
return nil, err | ||
} | ||
} | ||
} | ||
|
||
return conn, nil | ||
} | ||
|
||
func (s *iptablesServer) Close(ctx context.Context, conn *networkservice.Connection) (*empty.Empty, error) { | ||
_, err := next.Server(ctx).Close(ctx, conn) | ||
|
||
var restoreErr error | ||
ctxMap := metadata.Map(ctx, metadata.IsClient(s)) | ||
if initialRules, rulesWasApplied := ctxMap.Load(applyIPTablesKey{}); rulesWasApplied { | ||
restoreErr = s.manager.Restore(initialRules.(string)) | ||
} | ||
|
||
if err != nil && restoreErr != nil { | ||
return nil, errors.Wrap(err, restoreErr.Error()) | ||
} | ||
if restoreErr != nil { | ||
return nil, restoreErr | ||
} | ||
|
||
return &empty.Empty{}, err | ||
} |