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

Added WireGuard dialer #143

Merged
merged 4 commits into from
Jul 30, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
21 changes: 21 additions & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,24 @@ This project uses font from https://www.onlygfx.com/newspaper-cutout-font-white-

This project uses software from https://github.com/oschwald/maxminddb-golang (ISC)
* Copyright (c) 2015, Gregory J. Oschwald <[email protected]>

This project uses software from https://git.zx2c4.com/wireguard-go/about/ (MIT)
* Copyright (C) 2017-2023 WireGuard LLC. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,27 @@ Fabric that holds application components together.
* `state` - where data persists on disk through restarts of the application. Default is `.slrp/data` of your home directory.
* `sync` - how often data is synchronised to disk, pending availability of any updates of component state. Default is every minute.

## dialer

[WireGuard](https://www.wireguard.com/) userspace VPN dialer configuration. Embeds the official [Go implementation](https://git.zx2c4.com/wireguard-go). Disabled by default.

* `wireguard_config_file` - [configuration file](https://www.wireguard.com/#cryptokey-routing) from WireGuard. IPv6 address parsing is ignored at the moment.
* `wireguard_verbose` - verbose logging mode for WireGuard tunnel.

Sample WireGuard configuration file:

```ini
[Interface]
PrivateKey = gI6EdUSYvn8ugXOt8QQD6Yc+JyiZxIhp3GInSWRfWGE=
Address = 1.2.3.4/24
DNS = 1.2.3.4

[Peer]
PublicKey = HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw=
Endpoint = 1.2.3.4:51820
AllowedIPs = 0.0.0.0/0
```

## log

Structured logging meta-components.
Expand Down
117 changes: 68 additions & 49 deletions checker/checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ import (
"fmt"
"io/ioutil"
"math/rand"
"net"
"net/http"
"regexp"
"strings"
"time"

"github.com/nfx/slrp/app"
"github.com/nfx/slrp/pmux"
"github.com/rs/zerolog/log"

"github.com/corpix/uarand"
"github.com/microcosm-cc/bluemonday"
Expand All @@ -22,6 +24,14 @@ type Checker interface {
Check(ctx context.Context, proxy pmux.Proxy) (time.Duration, error)
}

type dialer interface {
DialContext(ctx context.Context, network, address string) (net.Conn, error)
}

type httpClient interface {
Do(req *http.Request) (*http.Response, error)
}

var (
firstPass = []string{
// these check for ext ip, but don't show headers
Expand All @@ -44,57 +54,81 @@ var (
ErrNotAnonymous = fmt.Errorf("this IP address found")
)

var defaultClient httpClient = pmux.DefaultHttpClient

func init() {
defaultClient = &http.Client{
Transport: pmux.ContextualHttpTransport(),
Timeout: 5 * time.Second,
}
}

func NewChecker() Checker {
ip, err := thisIP()
if err != nil {
panic(fmt.Errorf("cannot get this IP: %w", err))
}
func NewChecker(dialer dialer) Checker {
return &configurableChecker{
ip: ip,
client: defaultClient,
strategies: map[string]Checker{
"twopass": newTwoPass(ip, defaultClient),
"simple": newFederated(firstPass, defaultClient, ip),
"headers": newFederated([]string{
"https://ifconfig.me/all",
"https://ifconfig.io/all.json",
}, defaultClient, ip),
client: &http.Client{
Timeout: 5 * time.Second,
Transport: &http.Transport{
DialContext: dialer.DialContext,
TLSClientConfig: pmux.DefaultTlsConfig,
Proxy: pmux.ProxyFromContext,
},
},
strategy: "simple",
}
}

type configurableChecker struct {
ip string
client httpClient
strategies map[string]Checker
strategy string
ip string
client httpClient
strategy Checker
}

func (cc *configurableChecker) Configure(conf app.Config) error {
cc.strategy = conf.StrOr("strategy", "simple")
_, invalidStrategy := cc.strategies[cc.strategy]
if !invalidStrategy {
return fmt.Errorf("invalid strategy: %s", cc.strategy)
ip, err := cc.thisIP()
if ip == "" {
return fmt.Errorf("IP is empty")
}
if err != nil {
return fmt.Errorf("cannot get this IP: %w", err)
}
cc.ip = ip
strategies := map[string]Checker{
"twopass": newTwoPass(ip, cc.client),
"simple": newFederated(firstPass, cc.client, ip),
"headers": newFederated([]string{
"https://ifconfig.me/all",
"https://ifconfig.io/all.json",
}, cc.client, ip),
}
strategyName := conf.StrOr("strategy", "simple")
strategy, ok := strategies[strategyName]
if !ok {
return fmt.Errorf("invalid strategy: %s", strategyName)
}
cc.strategy = strategy
timeout := conf.DurOr("timeout", 5*time.Second)
original, ok := cc.client.(*http.Client)
if ok {
original.Timeout = conf.DurOr("timeout", 5*time.Second)
original.Timeout = timeout
}
log.Info().
Str("ip", ip).
Str("strategy", strategyName).
Dur("timeout", timeout).
Msg("configured proxy checker")
return nil
}

func (cc *configurableChecker) thisIP() (string, error) {
req, err := http.NewRequest("GET", "https://ifconfig.me/ip", nil)
if err != nil {
return "", err
}
r, err := cc.client.Do(req)
if err != nil {
return "", err
}
defer r.Body.Close()
s := bufio.NewScanner(r.Body)
s.Scan()
return s.Text(), nil
}

func (cc *configurableChecker) Check(ctx context.Context, proxy pmux.Proxy) (time.Duration, error) {
return cc.strategies[cc.strategy].Check(ctx, proxy)
if cc.strategy == nil {
return 0, fmt.Errorf("no strategy")
}
return cc.strategy.Check(ctx, proxy)
}

func newTwoPass(ip string, client httpClient) twoPass {
Expand Down Expand Up @@ -158,10 +192,6 @@ func (f federated) Check(ctx context.Context, proxy pmux.Proxy) (time.Duration,
return f[choice].Check(ctx, proxy)
}

type httpClient interface {
Do(req *http.Request) (*http.Response, error)
}

type simple struct {
client httpClient
page string
Expand Down Expand Up @@ -233,17 +263,6 @@ func truncatedBody(body string) string {
return body
}

func thisIP() (string, error) {
r, err := http.Get("https://ifconfig.me/ip")
if err != nil {
return "", err
}
defer r.Body.Close()
s := bufio.NewScanner(r.Body)
s.Scan()
return s.Text(), nil
}

type temporary string

func (t temporary) Temporary() bool {
Expand Down
29 changes: 14 additions & 15 deletions checker/checker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"fmt"
"io"
"net"
"net/http"
"strings"
"testing"
Expand All @@ -16,39 +17,37 @@ import (
)

func TestFailure(t *testing.T) {
defaultClient = &staticResponseClient{
c := NewChecker(&checkerShim{
err: fmt.Errorf("fails"),
}
c := NewChecker()

})
ctx := context.Background()
_, err := c.Check(ctx, pmux.HttpProxy("127.0.0.1:1"))
assert.EqualError(t, err, "fails")
assert.EqualError(t, err, "no strategy")
}

func TestConfigurableChecker(t *testing.T) {
client := http.DefaultClient
c := configurableChecker{
c := &configurableChecker{
client: client,
strategies: map[string]Checker{
"simple": &simple{}, // just for tests
},
}
err := c.Configure(app.Config{})
assert.NoError(t, err)
assert.Equal(t, "simple", c.strategy)
assert.Equal(t, time.Second*5, client.Timeout)
}

type staticResponseClient struct {
type checkerShim struct {
http.Response
err error
}

func (r staticResponseClient) Do(req *http.Request) (*http.Response, error) {
func (r checkerShim) Do(req *http.Request) (*http.Response, error) {
return &r.Response, r.err
}

func (r checkerShim) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
return nil, r.err
}

func body(x string) io.ReadCloser {
return io.NopCloser(bytes.NewBufferString(x))
}
Expand Down Expand Up @@ -90,7 +89,7 @@ func TestTwoPassCheck(t *testing.T) {
&simple{
ip: "XYZ",
valid: "..",
client: staticResponseClient{
client: checkerShim{
Response: http.Response{
Body: body(tt.firstBody),
StatusCode: 200,
Expand All @@ -103,7 +102,7 @@ func TestTwoPassCheck(t *testing.T) {
&simple{
ip: "XYZ",
valid: "..",
client: staticResponseClient{
client: checkerShim{
Response: http.Response{
Body: body(tt.secondBody),
StatusCode: 200,
Expand Down Expand Up @@ -197,7 +196,7 @@ func TestSimpleCheck(t *testing.T) {
ip: "255.0.0.1",
valid: tt.valid,
page: tt.page,
client: staticResponseClient{
client: checkerShim{
Response: http.Response{
Body: tt.body,
StatusCode: 200,
Expand Down
Loading