From 009a3a74afd4512f8f394f0873764e380264ee77 Mon Sep 17 00:00:00 2001 From: Nicholas Helke Date: Mon, 21 May 2018 12:51:21 +0100 Subject: [PATCH] Make `P()` and `G()` return copied `big.Int`s so they can't be accidentally or maliciously mutated --- dhgroup.go | 8 ++++++-- dhkx_test.go | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/dhgroup.go b/dhgroup.go index fdc1e8c..e8d84a8 100644 --- a/dhgroup.go +++ b/dhgroup.go @@ -30,11 +30,15 @@ type DHGroup struct { } func (self *DHGroup) P() *big.Int { - return self.p + p := new(big.Int) + p.Set(self.p) + return p } func (self *DHGroup) G() *big.Int { - return self.g + g := new(big.Int) + g.Set(self.g) + return g } func (self *DHGroup) GeneratePrivateKey(randReader io.Reader) (key *DHKey, err error) { diff --git a/dhkx_test.go b/dhkx_test.go index aad31da..478a5d3 100644 --- a/dhkx_test.go +++ b/dhkx_test.go @@ -101,3 +101,21 @@ func TestCustomGroupKeyExchange(t *testing.T) { t.Errorf("%v", err) } } + +func TestPIsNotMutable(t *testing.T) { + d, _ := GetGroup(0) + p := d.p.String() + d.P().Set(big.NewInt(1)) + if p != d.p.String() { + t.Errorf("group's prime mutated externally, should be %s, was changed to %s", p, d.p.String()) + } +} + +func TestGIsNotMutable(t *testing.T) { + d, _ := GetGroup(0) + g := d.g.String() + d.G().Set(big.NewInt(0)) + if g != d.g.String() { + t.Errorf("group's generator mutated externally, should be %s, was changed to %s", g, d.g.String()) + } +}