golang.zx2c4.com/wireguard/windows@v0.5.4-0.20230123132234-dcc0eb72a04b/conf/config.go (about)

     1  /* SPDX-License-Identifier: MIT
     2   *
     3   * Copyright (C) 2019-2022 WireGuard LLC. All Rights Reserved.
     4   */
     5  
     6  package conf
     7  
     8  import (
     9  	"crypto/rand"
    10  	"crypto/subtle"
    11  	"encoding/base64"
    12  	"fmt"
    13  	"net/netip"
    14  	"strings"
    15  	"time"
    16  
    17  	"golang.org/x/crypto/curve25519"
    18  
    19  	"golang.zx2c4.com/wireguard/windows/l18n"
    20  )
    21  
    22  const KeyLength = 32
    23  
    24  type Endpoint struct {
    25  	Host string
    26  	Port uint16
    27  }
    28  
    29  type (
    30  	Key           [KeyLength]byte
    31  	HandshakeTime time.Duration
    32  	Bytes         uint64
    33  )
    34  
    35  type Config struct {
    36  	Name      string
    37  	Interface Interface
    38  	Peers     []Peer
    39  }
    40  
    41  type Interface struct {
    42  	PrivateKey Key
    43  	Addresses  []netip.Prefix
    44  	ListenPort uint16
    45  	MTU        uint16
    46  	DNS        []netip.Addr
    47  	DNSSearch  []string
    48  	PreUp      string
    49  	PostUp     string
    50  	PreDown    string
    51  	PostDown   string
    52  	TableOff   bool
    53  }
    54  
    55  type Peer struct {
    56  	PublicKey           Key
    57  	PresharedKey        Key
    58  	AllowedIPs          []netip.Prefix
    59  	Endpoint            Endpoint
    60  	PersistentKeepalive uint16
    61  
    62  	RxBytes           Bytes
    63  	TxBytes           Bytes
    64  	LastHandshakeTime HandshakeTime
    65  }
    66  
    67  func (conf *Config) IntersectsWith(other *Config) bool {
    68  	allRoutes := make(map[netip.Prefix]bool, len(conf.Interface.Addresses)*2+len(conf.Peers)*3)
    69  	for _, a := range conf.Interface.Addresses {
    70  		allRoutes[netip.PrefixFrom(a.Addr(), a.Addr().BitLen())] = true
    71  		allRoutes[a.Masked()] = true
    72  	}
    73  	for i := range conf.Peers {
    74  		for _, a := range conf.Peers[i].AllowedIPs {
    75  			allRoutes[a.Masked()] = true
    76  		}
    77  	}
    78  	for _, a := range other.Interface.Addresses {
    79  		if allRoutes[netip.PrefixFrom(a.Addr(), a.Addr().BitLen())] {
    80  			return true
    81  		}
    82  		if allRoutes[a.Masked()] {
    83  			return true
    84  		}
    85  	}
    86  	for i := range other.Peers {
    87  		for _, a := range other.Peers[i].AllowedIPs {
    88  			if allRoutes[a.Masked()] {
    89  				return true
    90  			}
    91  		}
    92  	}
    93  	return false
    94  }
    95  
    96  func (e *Endpoint) String() string {
    97  	if strings.IndexByte(e.Host, ':') != -1 {
    98  		return fmt.Sprintf("[%s]:%d", e.Host, e.Port)
    99  	}
   100  	return fmt.Sprintf("%s:%d", e.Host, e.Port)
   101  }
   102  
   103  func (e *Endpoint) IsEmpty() bool {
   104  	return len(e.Host) == 0
   105  }
   106  
   107  func (k *Key) String() string {
   108  	return base64.StdEncoding.EncodeToString(k[:])
   109  }
   110  
   111  func (k *Key) IsZero() bool {
   112  	var zeros Key
   113  	return subtle.ConstantTimeCompare(zeros[:], k[:]) == 1
   114  }
   115  
   116  func (k *Key) Public() *Key {
   117  	var p [KeyLength]byte
   118  	curve25519.ScalarBaseMult(&p, (*[KeyLength]byte)(k))
   119  	return (*Key)(&p)
   120  }
   121  
   122  func NewPresharedKey() (*Key, error) {
   123  	var k [KeyLength]byte
   124  	_, err := rand.Read(k[:])
   125  	if err != nil {
   126  		return nil, err
   127  	}
   128  	return (*Key)(&k), nil
   129  }
   130  
   131  func NewPrivateKey() (*Key, error) {
   132  	k, err := NewPresharedKey()
   133  	if err != nil {
   134  		return nil, err
   135  	}
   136  	k[0] &= 248
   137  	k[31] = (k[31] & 127) | 64
   138  	return k, nil
   139  }
   140  
   141  func NewPrivateKeyFromString(b64 string) (*Key, error) {
   142  	return parseKeyBase64(b64)
   143  }
   144  
   145  func (t HandshakeTime) IsEmpty() bool {
   146  	return t == HandshakeTime(0)
   147  }
   148  
   149  func (t HandshakeTime) String() string {
   150  	u := time.Unix(0, 0).Add(time.Duration(t)).Unix()
   151  	n := time.Now().Unix()
   152  	if u == n {
   153  		return l18n.Sprintf("Now")
   154  	} else if u > n {
   155  		return l18n.Sprintf("System clock wound backward!")
   156  	}
   157  	left := n - u
   158  	years := left / (365 * 24 * 60 * 60)
   159  	left = left % (365 * 24 * 60 * 60)
   160  	days := left / (24 * 60 * 60)
   161  	left = left % (24 * 60 * 60)
   162  	hours := left / (60 * 60)
   163  	left = left % (60 * 60)
   164  	minutes := left / 60
   165  	seconds := left % 60
   166  	s := make([]string, 0, 5)
   167  	if years > 0 {
   168  		s = append(s, l18n.Sprintf("%d year(s)", years))
   169  	}
   170  	if days > 0 {
   171  		s = append(s, l18n.Sprintf("%d day(s)", days))
   172  	}
   173  	if hours > 0 {
   174  		s = append(s, l18n.Sprintf("%d hour(s)", hours))
   175  	}
   176  	if minutes > 0 {
   177  		s = append(s, l18n.Sprintf("%d minute(s)", minutes))
   178  	}
   179  	if seconds > 0 {
   180  		s = append(s, l18n.Sprintf("%d second(s)", seconds))
   181  	}
   182  	timestamp := strings.Join(s, l18n.UnitSeparator())
   183  	return l18n.Sprintf("%s ago", timestamp)
   184  }
   185  
   186  func (b Bytes) String() string {
   187  	if b < 1024 {
   188  		return l18n.Sprintf("%d\u00a0B", b)
   189  	} else if b < 1024*1024 {
   190  		return l18n.Sprintf("%.2f\u00a0KiB", float64(b)/1024)
   191  	} else if b < 1024*1024*1024 {
   192  		return l18n.Sprintf("%.2f\u00a0MiB", float64(b)/(1024*1024))
   193  	} else if b < 1024*1024*1024*1024 {
   194  		return l18n.Sprintf("%.2f\u00a0GiB", float64(b)/(1024*1024*1024))
   195  	}
   196  	return l18n.Sprintf("%.2f\u00a0TiB", float64(b)/(1024*1024*1024)/1024)
   197  }
   198  
   199  func (conf *Config) DeduplicateNetworkEntries() {
   200  	m := make(map[string]bool, len(conf.Interface.Addresses))
   201  	i := 0
   202  	for _, addr := range conf.Interface.Addresses {
   203  		s := addr.String()
   204  		if m[s] {
   205  			continue
   206  		}
   207  		m[s] = true
   208  		conf.Interface.Addresses[i] = addr
   209  		i++
   210  	}
   211  	conf.Interface.Addresses = conf.Interface.Addresses[:i]
   212  
   213  	m = make(map[string]bool, len(conf.Interface.DNS))
   214  	i = 0
   215  	for _, addr := range conf.Interface.DNS {
   216  		s := addr.String()
   217  		if m[s] {
   218  			continue
   219  		}
   220  		m[s] = true
   221  		conf.Interface.DNS[i] = addr
   222  		i++
   223  	}
   224  	conf.Interface.DNS = conf.Interface.DNS[:i]
   225  
   226  	for _, peer := range conf.Peers {
   227  		m = make(map[string]bool, len(peer.AllowedIPs))
   228  		i = 0
   229  		for _, addr := range peer.AllowedIPs {
   230  			s := addr.String()
   231  			if m[s] {
   232  				continue
   233  			}
   234  			m[s] = true
   235  			peer.AllowedIPs[i] = addr
   236  			i++
   237  		}
   238  		peer.AllowedIPs = peer.AllowedIPs[:i]
   239  	}
   240  }
   241  
   242  func (conf *Config) Redact() {
   243  	conf.Interface.PrivateKey = Key{}
   244  	for i := range conf.Peers {
   245  		conf.Peers[i].PublicKey = Key{}
   246  		conf.Peers[i].PresharedKey = Key{}
   247  	}
   248  }