66package device
77
88import (
9+ "encoding/base64"
10+ "fmt"
11+ "io"
912 "runtime"
1013 "sync"
1114 "sync/atomic"
@@ -17,6 +20,8 @@ import (
1720 "golang.zx2c4.com/wireguard/tun"
1821)
1922
23+ type HandshakeHandler func (t time.Time , ls NoisePrivateKey , rs NoisePublicKey , le NoisePrivateKey , ps NoisePresharedKey )
24+
2025type Device struct {
2126 state struct {
2227 // state holds the device's state. It is accessed atomically.
@@ -85,6 +90,8 @@ type Device struct {
8590 mtu int32
8691 }
8792
93+ keyLogHandler HandshakeHandler
94+
8895 ipcMutex sync.RWMutex
8996 closed chan struct {}
9097 log * Logger
@@ -94,10 +101,9 @@ type Device struct {
94101// There are three states: down, up, closed.
95102// Transitions:
96103//
97- // down -----+
98- // ↑↓ ↓
99- // up -> closed
100- //
104+ // down -----+
105+ // ↑↓ ↓
106+ // up -> closed
101107type deviceState uint32
102108
103109//go:generate go run golang.org/x/tools/cmd/stringer -type deviceState -trimprefix=deviceState
@@ -523,3 +529,26 @@ func (device *Device) BindClose() error {
523529 device .net .Unlock ()
524530 return err
525531}
532+
533+ func (device * Device ) OnHandshake (hdlr HandshakeHandler ) {
534+ device .keyLogHandler = hdlr
535+ }
536+
537+ func (device * Device ) WriteKeyLog (wr io.Writer ) {
538+ mu := sync.Mutex {}
539+
540+ device .OnHandshake (func (t time.Time , ls NoisePrivateKey , rs NoisePublicKey , le NoisePrivateKey , ps NoisePresharedKey ) {
541+ mu .Lock ()
542+ defer mu .Unlock ()
543+
544+ fmt .Fprintf (wr , "LOCAL_STATIC_PRIVATE_KEY=%s\n " , base64 .StdEncoding .EncodeToString (ls [:]))
545+ fmt .Fprintf (wr , "REMOTE_STATIC_PUBLIC_KEY=%s\n " , base64 .StdEncoding .EncodeToString (rs [:]))
546+ fmt .Fprintf (wr , "LOCAL_EPHEMERAL_PRIVATE_KEY=%s\n " , base64 .StdEncoding .EncodeToString (le [:]))
547+
548+ if ! ps .IsZero () {
549+ fmt .Fprintf (wr , "PRESHARED_KEY=%s\n " , base64 .StdEncoding .EncodeToString (ps [:]))
550+ }
551+
552+ device .log .Verbosef ("Writing new ephemeral key to keylog" )
553+ })
554+ }
0 commit comments