Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
45460e0797 | ||
|
|
d37c95e27d | ||
|
|
e2ffffe738 | ||
|
|
60e158ad30 | ||
|
|
1b77d23dc8 | ||
|
|
3872a2bc69 | ||
|
|
9f72eccdf6 | ||
|
|
8f405a4109 | ||
|
|
bb41b3dbe6 | ||
|
|
e04e721997 | ||
|
|
b315afd69a | ||
|
|
d4a85f4749 | ||
|
|
6f39c5226a | ||
|
|
4c4d20b72c | ||
|
|
e3e62d9601 | ||
|
|
5adb68b3e6 | ||
|
|
9beb694f97 | ||
|
|
e5306b2f3e | ||
|
|
d2fe592df1 | ||
|
|
d59570d1a3 | ||
|
|
4aab0d9d6a | ||
|
|
a1c0d99298 | ||
|
|
3c7c86938f | ||
|
|
533fb3f7e4 | ||
|
|
abbc44d451 | ||
|
|
e052873987 | ||
|
|
b61cf853a8 | ||
|
|
9c2cd33e8d | ||
|
|
890731877d | ||
|
|
ffd87b4878 | ||
|
|
4e7a7384ec | ||
|
|
b25012b37b | ||
|
|
6c195c8a97 | ||
|
|
f717e29698 | ||
|
|
e7c36ccb47 | ||
|
|
0fb843a472 | ||
|
|
e3d1254f1e | ||
|
|
a1ce0fee12 | ||
|
|
a749d17980 | ||
|
|
7ee59707ff | ||
|
|
44decbfe70 | ||
|
|
b8a14a8d65 | ||
|
|
9d9d507896 | ||
|
|
fd0b90d21f | ||
|
|
b9e53593a6 | ||
|
|
cc0e4fc1d4 | ||
|
|
a8e9237a21 | ||
|
|
03ca0dcccb | ||
|
|
8400f4a938 | ||
|
|
81c6cb34a8 | ||
|
|
982eaa62df | ||
|
|
159944f128 | ||
|
|
a408498e55 | ||
|
|
cab0f71854 | ||
|
|
2f26647a79 | ||
|
|
e08b06753d | ||
|
|
7d0074ccc6 | ||
|
|
506e022208 | ||
|
|
7dacc380ba | ||
|
|
19acf81bd7 | ||
|
|
3a1c6b4b61 | ||
|
|
f4602e4040 | ||
|
|
4e0068c009 | ||
|
|
e79546e28b | ||
|
|
f91f7a7c31 | ||
|
|
2df4153a03 | ||
|
|
bcf6a849ef | ||
|
|
b4f2b62076 | ||
|
|
79ec3a51fc | ||
|
|
122a78f140 | ||
|
|
c0531f9c34 | ||
|
|
0997000b45 | ||
|
|
017a1aaa2d | ||
|
|
cf29fa96f8 | ||
|
|
0b7aa0cfb0 | ||
|
|
1faea2975c | ||
|
|
627cb894b6 | ||
|
|
dca4914afe | ||
|
|
1336e21bd6 | ||
|
|
2beaa59a3c | ||
|
|
66c3d8ce71 | ||
|
|
ddb4e80c6a | ||
|
|
f4d47b0db5 | ||
|
|
96dc232fbd | ||
|
|
8c9ba31836 | ||
|
|
559e062ce8 | ||
|
|
5307a0ce6d | ||
|
|
9d779377cf | ||
|
|
8f580defa0 | ||
|
|
a4d1237429 | ||
|
|
b8d8dae13d | ||
|
|
f5a2eabcab | ||
|
|
44ecf3af99 | ||
|
|
ef5341b706 | ||
|
|
b999374650 | ||
|
|
c247dead11 | ||
|
|
1fda73153f | ||
|
|
1b4c3d2e8c | ||
|
|
b903b535d3 |
+1
-1
@@ -690,7 +690,7 @@ func (c *Client) addNonce(h http.Header) {
|
||||
}
|
||||
|
||||
func (c *Client) fetchNonce(ctx context.Context, url string) (string, error) {
|
||||
r, err := http.NewRequest("HEAD", url, nil)
|
||||
r, err := http.NewRequestWithContext(ctx, "HEAD", url, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -134,7 +134,8 @@ type Manager struct {
|
||||
// RenewBefore optionally specifies how early certificates should
|
||||
// be renewed before they expire.
|
||||
//
|
||||
// If zero, they're renewed 30 days before expiration.
|
||||
// If zero, they're renewed at the lesser of 30 days or
|
||||
// 1/3 of the certificate lifetime.
|
||||
RenewBefore time.Duration
|
||||
|
||||
// Client is used to perform low-level operations, such as account registration
|
||||
@@ -247,10 +248,6 @@ func (m *Manager) TLSConfig() *tls.Config {
|
||||
// If GetCertificate is used directly, instead of via Manager.TLSConfig, package users will
|
||||
// also have to add acme.ALPNProto to NextProtos for tls-alpn-01, or use HTTPHandler for http-01.
|
||||
func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
if m.Prompt == nil {
|
||||
return nil, errors.New("acme/autocert: Manager.Prompt not set")
|
||||
}
|
||||
|
||||
name := hello.ServerName
|
||||
if name == "" {
|
||||
return nil, errors.New("acme/autocert: missing server name")
|
||||
@@ -464,7 +461,7 @@ func (m *Manager) cert(ctx context.Context, ck certKey) (*tls.Certificate, error
|
||||
leaf: cert.Leaf,
|
||||
}
|
||||
m.state[ck] = s
|
||||
m.startRenew(ck, s.key, s.leaf.NotAfter)
|
||||
m.startRenew(ck, s.key, s.leaf.NotBefore, s.leaf.NotAfter)
|
||||
return cert, nil
|
||||
}
|
||||
|
||||
@@ -610,7 +607,7 @@ func (m *Manager) createCert(ctx context.Context, ck certKey) (*tls.Certificate,
|
||||
}
|
||||
state.cert = der
|
||||
state.leaf = leaf
|
||||
m.startRenew(ck, state.key, state.leaf.NotAfter)
|
||||
m.startRenew(ck, state.key, state.leaf.NotBefore, state.leaf.NotAfter)
|
||||
return state.tlscert()
|
||||
}
|
||||
|
||||
@@ -908,7 +905,7 @@ func httpTokenCacheKey(tokenPath string) string {
|
||||
//
|
||||
// The key argument is a certificate private key.
|
||||
// The exp argument is the cert expiration time (NotAfter).
|
||||
func (m *Manager) startRenew(ck certKey, key crypto.Signer, exp time.Time) {
|
||||
func (m *Manager) startRenew(ck certKey, key crypto.Signer, notBefore, notAfter time.Time) {
|
||||
m.renewalMu.Lock()
|
||||
defer m.renewalMu.Unlock()
|
||||
if m.renewal[ck] != nil {
|
||||
@@ -920,7 +917,7 @@ func (m *Manager) startRenew(ck certKey, key crypto.Signer, exp time.Time) {
|
||||
}
|
||||
dr := &domainRenewal{m: m, ck: ck, key: key}
|
||||
m.renewal[ck] = dr
|
||||
dr.start(exp)
|
||||
dr.start(notBefore, notAfter)
|
||||
}
|
||||
|
||||
// stopRenew stops all currently running cert renewal timers.
|
||||
@@ -1028,13 +1025,6 @@ func (m *Manager) hostPolicy() HostPolicy {
|
||||
return defaultHostPolicy
|
||||
}
|
||||
|
||||
func (m *Manager) renewBefore() time.Duration {
|
||||
if m.RenewBefore > renewJitter {
|
||||
return m.RenewBefore
|
||||
}
|
||||
return 720 * time.Hour // 30 days
|
||||
}
|
||||
|
||||
func (m *Manager) now() time.Time {
|
||||
if m.nowFunc != nil {
|
||||
return m.nowFunc()
|
||||
|
||||
@@ -201,7 +201,7 @@ func TestGetCertificate(t *testing.T) {
|
||||
prepare: func(t *testing.T, man *Manager, s *acmetest.CAServer) {
|
||||
man.Prompt = nil
|
||||
},
|
||||
expectError: "Manager.Prompt not set",
|
||||
expectError: "missing Manager.Prompt",
|
||||
},
|
||||
{
|
||||
name: "trailingDot",
|
||||
@@ -561,9 +561,9 @@ func TestHTTPHandlerDefaultFallback(t *testing.T) {
|
||||
{"GET", "http://example.org/foo?a=b", 302, "https://example.org/foo?a=b"},
|
||||
{"GET", "http://example.org:80/foo?a=b", 302, "https://example.org:443/foo?a=b"},
|
||||
{"GET", "http://example.org:80/foo%20bar", 302, "https://example.org:443/foo%20bar"},
|
||||
{"GET", "http://[2602:d1:xxxx::c60a]:1234", 302, "https://[2602:d1:xxxx::c60a]:443/"},
|
||||
{"GET", "http://[2602:d1:xxxx::c60a]", 302, "https://[2602:d1:xxxx::c60a]/"},
|
||||
{"GET", "http://[2602:d1:xxxx::c60a]/foo?a=b", 302, "https://[2602:d1:xxxx::c60a]/foo?a=b"},
|
||||
{"GET", "http://[2602:d1:abcd::c60a]:1234", 302, "https://[2602:d1:abcd::c60a]:443/"},
|
||||
{"GET", "http://[2602:d1:abcd::c60a]", 302, "https://[2602:d1:abcd::c60a]/"},
|
||||
{"GET", "http://[2602:d1:abcd::c60a]/foo?a=b", 302, "https://[2602:d1:abcd::c60a]/foo?a=b"},
|
||||
{"HEAD", "http://example.org", 302, "https://example.org/"},
|
||||
{"HEAD", "http://example.org/foo", 302, "https://example.org/foo"},
|
||||
{"HEAD", "http://example.org/foo/bar/", 302, "https://example.org/foo/bar/"},
|
||||
|
||||
@@ -145,7 +145,7 @@ func (ca *CAServer) URL() string {
|
||||
return ca.url
|
||||
}
|
||||
|
||||
// Roots returns a pool cointaining the CA root.
|
||||
// Roots returns a pool containing the CA root.
|
||||
func (ca *CAServer) Roots() *x509.CertPool {
|
||||
if ca.url == "" {
|
||||
panic("Roots called before Start")
|
||||
@@ -239,7 +239,8 @@ type discovery struct {
|
||||
}
|
||||
|
||||
type discoveryMeta struct {
|
||||
ExternalAccountRequired bool `json:"externalAccountRequired,omitempty"`
|
||||
Terms string `json:"termsOfService,omitempty"`
|
||||
ExternalAccountRequired bool `json:"externalAccountRequired,omitempty"`
|
||||
}
|
||||
|
||||
type challenge struct {
|
||||
@@ -281,6 +282,7 @@ func (ca *CAServer) handle(w http.ResponseWriter, r *http.Request) {
|
||||
NewAccount: ca.serverURL("/new-account"),
|
||||
NewOrder: ca.serverURL("/new-order"),
|
||||
Meta: discoveryMeta{
|
||||
Terms: ca.serverURL("/terms"),
|
||||
ExternalAccountRequired: ca.eabRequired,
|
||||
},
|
||||
}
|
||||
|
||||
+19
-17
@@ -11,9 +11,6 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// renewJitter is the maximum deviation from Manager.RenewBefore.
|
||||
const renewJitter = time.Hour
|
||||
|
||||
// domainRenewal tracks the state used by the periodic timers
|
||||
// renewing a single domain's cert.
|
||||
type domainRenewal struct {
|
||||
@@ -30,13 +27,13 @@ type domainRenewal struct {
|
||||
// defined by the certificate expiration time exp.
|
||||
//
|
||||
// If the timer is already started, calling start is a noop.
|
||||
func (dr *domainRenewal) start(exp time.Time) {
|
||||
func (dr *domainRenewal) start(notBefore, notAfter time.Time) {
|
||||
dr.timerMu.Lock()
|
||||
defer dr.timerMu.Unlock()
|
||||
if dr.timer != nil {
|
||||
return
|
||||
}
|
||||
dr.timer = time.AfterFunc(dr.next(exp), dr.renew)
|
||||
dr.timer = time.AfterFunc(dr.next(notBefore, notAfter), dr.renew)
|
||||
}
|
||||
|
||||
// stop stops the cert renewal timer and waits for any in-flight calls to renew
|
||||
@@ -79,7 +76,7 @@ func (dr *domainRenewal) renew() {
|
||||
// TODO: rotate dr.key at some point?
|
||||
next, err := dr.do(ctx)
|
||||
if err != nil {
|
||||
next = renewJitter / 2
|
||||
next = time.Hour / 2
|
||||
next += time.Duration(pseudoRand.int63n(int64(next)))
|
||||
}
|
||||
testDidRenewLoop(next, err)
|
||||
@@ -107,8 +104,8 @@ func (dr *domainRenewal) do(ctx context.Context) (time.Duration, error) {
|
||||
// a race is likely unavoidable in a distributed environment
|
||||
// but we try nonetheless
|
||||
if tlscert, err := dr.m.cacheGet(ctx, dr.ck); err == nil {
|
||||
next := dr.next(tlscert.Leaf.NotAfter)
|
||||
if next > dr.m.renewBefore()+renewJitter {
|
||||
next := dr.next(tlscert.Leaf.NotBefore, tlscert.Leaf.NotAfter)
|
||||
if next > 0 {
|
||||
signer, ok := tlscert.PrivateKey.(crypto.Signer)
|
||||
if ok {
|
||||
state := &certState{
|
||||
@@ -139,18 +136,23 @@ func (dr *domainRenewal) do(ctx context.Context) (time.Duration, error) {
|
||||
return 0, err
|
||||
}
|
||||
dr.updateState(state)
|
||||
return dr.next(leaf.NotAfter), nil
|
||||
return dr.next(leaf.NotBefore, leaf.NotAfter), nil
|
||||
}
|
||||
|
||||
func (dr *domainRenewal) next(expiry time.Time) time.Duration {
|
||||
d := expiry.Sub(dr.m.now()) - dr.m.renewBefore()
|
||||
// add a bit of randomness to renew deadline
|
||||
n := pseudoRand.int63n(int64(renewJitter))
|
||||
d -= time.Duration(n)
|
||||
if d < 0 {
|
||||
return 0
|
||||
// next returns the wait time before the next renewal should start.
|
||||
// If manager.RenewBefore is set, it uses that capped at 30 days,
|
||||
// otherwise it uses a default of 1/3 of the cert lifetime.
|
||||
// It builds in a jitter of 10% of the renew threshold, capped at 1 hour.
|
||||
func (dr *domainRenewal) next(notBefore, notAfter time.Time) time.Duration {
|
||||
threshold := min(notAfter.Sub(notBefore)/3, 30*24*time.Hour)
|
||||
if dr.m.RenewBefore > 0 {
|
||||
threshold = min(dr.m.RenewBefore, 30*24*time.Hour)
|
||||
}
|
||||
return d
|
||||
maxJitter := min(threshold/10, time.Hour)
|
||||
jitter := pseudoRand.int63n(int64(maxJitter))
|
||||
renewAt := notAfter.Add(-(threshold - time.Duration(jitter)))
|
||||
renewWait := renewAt.Sub(dr.m.now())
|
||||
return max(0, renewWait)
|
||||
}
|
||||
|
||||
var testDidRenewLoop = func(next time.Duration, err error) {}
|
||||
|
||||
@@ -17,27 +17,60 @@ import (
|
||||
|
||||
func TestRenewalNext(t *testing.T) {
|
||||
now := time.Now()
|
||||
man := &Manager{
|
||||
RenewBefore: 7 * 24 * time.Hour,
|
||||
nowFunc: func() time.Time { return now },
|
||||
}
|
||||
defer man.stopRenew()
|
||||
nowFn := func() time.Time { return now }
|
||||
tt := []struct {
|
||||
expiry time.Time
|
||||
min, max time.Duration
|
||||
name string
|
||||
renewBefore time.Duration // arg to Manager
|
||||
// leaf cert validity
|
||||
notBefore time.Time
|
||||
validFor time.Duration
|
||||
// wait time
|
||||
waitMin, waitMax time.Duration
|
||||
}{
|
||||
{now.Add(90 * 24 * time.Hour), 83*24*time.Hour - renewJitter, 83 * 24 * time.Hour},
|
||||
{now.Add(time.Hour), 0, 1},
|
||||
{now, 0, 1},
|
||||
{now.Add(-time.Hour), 0, 1},
|
||||
{"default renewal, 1h cert, valid",
|
||||
0, now, time.Hour, 40 * time.Minute, 50 * time.Minute},
|
||||
{"default renewal, 1h cert, should renew",
|
||||
0, now.Add(-50 * time.Minute), time.Hour, 0, 0},
|
||||
{"default renewal, 1h cert, expired",
|
||||
0, now.Add(-400 * 24 * time.Hour), time.Hour, 0, 0},
|
||||
{"default renewal, 6d cert, valid",
|
||||
0, now, 6 * 24 * time.Hour, 4 * 24 * time.Hour, (4*24 + 1) * time.Hour},
|
||||
{"default renewal, 6d cert, should renew",
|
||||
0, now.Add(-5 * 24 * time.Hour), 6 * 24 * time.Hour, 0, 0},
|
||||
{"default renewal, 6d cert, expired",
|
||||
0, now.Add(-400 * 24 * time.Hour), 6 * 24 * time.Hour, 0, 0},
|
||||
{"default renewal, 90d cert, valid",
|
||||
0, now, 90 * 24 * time.Hour, 60 * 24 * time.Hour, (60*24 + 1) * time.Hour},
|
||||
{"default renewal, 90d cert, should renew",
|
||||
0, now.Add(-70 * 24 * time.Hour), 90 * 24 * time.Hour, 0, 0},
|
||||
{"default renewal, 90d cert, expired",
|
||||
0, now.Add(-400 * 24 * time.Hour), 90 * 24 * time.Hour, 0, 0},
|
||||
{"default renewal, 398d cert, valid",
|
||||
0, now, 398 * 24 * time.Hour, (368 * 24) * time.Hour, (368*24 + 1) * time.Hour},
|
||||
{"default renewal, 398d cert, should renew",
|
||||
0, now.Add(-378 * 24 * time.Hour), 398 * 24 * time.Hour, 0, 0},
|
||||
{"default renewal, 398d cert, expired",
|
||||
0, now.Add(-400 * 24 * time.Hour), 398 * 24 * time.Hour, 0, 0},
|
||||
{"7d renewal, 90d cert, valid",
|
||||
7 * 24 * time.Hour, now, 90 * 24 * time.Hour, 83 * 24 * time.Hour, (83*24 + 1) * time.Hour},
|
||||
{"7d renewal, 90d cert, should not renew",
|
||||
7 * 24 * time.Hour, now.Add(-70 * 24 * time.Hour), 90 * 24 * time.Hour, 13 * 24 * time.Hour, (13*24 + 1) * time.Hour},
|
||||
{"7d renewal, 90d cert, should renew",
|
||||
7 * 24 * time.Hour, now.Add(-85 * 24 * time.Hour), 90 * 24 * time.Hour, 0, 0},
|
||||
{"7d renewal, 90d cert, expired",
|
||||
7 * 24 * time.Hour, now.Add(-400 * 24 * time.Hour), 90 * 24 * time.Hour, 0, 0},
|
||||
}
|
||||
|
||||
dr := &domainRenewal{m: man}
|
||||
for i, test := range tt {
|
||||
next := dr.next(test.expiry)
|
||||
if next < test.min || test.max < next {
|
||||
t.Errorf("%d: next = %v; want between %v and %v", i, next, test.min, test.max)
|
||||
}
|
||||
for _, test := range tt {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
dr := &domainRenewal{m: &Manager{RenewBefore: test.renewBefore, nowFunc: nowFn}}
|
||||
defer dr.m.stopRenew()
|
||||
|
||||
next := dr.next(test.notBefore, test.notBefore.Add(test.validFor))
|
||||
if next < test.waitMin || next > test.waitMax {
|
||||
t.Errorf("expected wait time: %v <= %v <= %v", test.waitMin, next, test.waitMax)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,9 +180,6 @@ func TestRenewFromCacheAlreadyRenewed(t *testing.T) {
|
||||
|
||||
// set internal state to an almost expired cert
|
||||
oldCert := ca.LeafCert(exampleDomain, "ECDSA", now.Add(-2*time.Hour), now.Add(time.Minute))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldLeaf, err := validCert(exampleCertKey, oldCert.Certificate, oldCert.PrivateKey.(crypto.Signer), now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -239,7 +269,7 @@ func TestRenewFromCacheAlreadyRenewed(t *testing.T) {
|
||||
}
|
||||
|
||||
// trigger renew
|
||||
man.startRenew(exampleCertKey, s.key, s.leaf.NotAfter)
|
||||
man.startRenew(exampleCertKey, s.key, s.leaf.NotBefore, s.leaf.NotAfter)
|
||||
<-renewed
|
||||
func() {
|
||||
man.renewalMu.Lock()
|
||||
|
||||
+2
-2
@@ -128,7 +128,7 @@ func wantStatus(codes ...int) resOkay {
|
||||
func (c *Client) get(ctx context.Context, url string, ok resOkay) (*http.Response, error) {
|
||||
retry := c.retryTimer()
|
||||
for {
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -228,7 +228,7 @@ func (c *Client) postNoRetry(ctx context.Context, key crypto.Signer, url string,
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
req, err := http.NewRequest("POST", url, bytes.NewReader(b))
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
+26
-6
@@ -382,7 +382,12 @@ func testIssuance(t *testing.T, env *environment, challSrv challengeServer) {
|
||||
// Wait for the order to become ready for finalization.
|
||||
order, err = client.WaitOrder(ctx, order.URI)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to wait for order %s: %s", orderURL, err)
|
||||
var orderErr *acme.OrderError
|
||||
if errors.Is(err, orderErr) {
|
||||
t.Fatalf("failed to wait for order %s: %s: %s", orderURL, err, orderErr.Problem)
|
||||
} else {
|
||||
t.Fatalf("failed to wait for order %s: %s", orderURL, err)
|
||||
}
|
||||
}
|
||||
if order.Status != acme.StatusReady {
|
||||
t.Fatalf("expected order %s status to be ready, got %v",
|
||||
@@ -692,14 +697,14 @@ func startPebbleEnvironment(t *testing.T, config *environmentConfig) environment
|
||||
func waitForServer(t *testing.T, addr string) {
|
||||
t.Helper()
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
for i := 0; i < 20; i++ {
|
||||
if conn, err := net.Dial("tcp", addr); err == nil {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Duration(i*100) * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("failed to connect to %q after 10 tries", addr)
|
||||
t.Fatalf("failed to connect to %q after 20 tries", addr)
|
||||
}
|
||||
|
||||
// fetchModule fetches the module at the given version and returns the directory
|
||||
@@ -752,7 +757,7 @@ func prepareBinaries(t *testing.T, pebbleDir string) string {
|
||||
|
||||
// We don't want to build in the module cache dir, which might not be
|
||||
// writable or to pollute the user's clone with binaries if pebbleLocalDir
|
||||
//is used.
|
||||
// is used.
|
||||
binDir := t.TempDir()
|
||||
|
||||
build := func(cmd string) {
|
||||
@@ -776,14 +781,29 @@ func prepareBinaries(t *testing.T, pebbleDir string) string {
|
||||
func spawnServerProcess(t *testing.T, dir string, cmd string, args ...string) {
|
||||
t.Helper()
|
||||
|
||||
var stdout, stderr bytes.Buffer
|
||||
|
||||
cmdInstance := exec.Command("./"+cmd, args...)
|
||||
cmdInstance.Dir = dir
|
||||
cmdInstance.Stdout = os.Stdout
|
||||
cmdInstance.Stderr = os.Stderr
|
||||
cmdInstance.Stdout = &stdout
|
||||
cmdInstance.Stderr = &stderr
|
||||
|
||||
if err := cmdInstance.Start(); err != nil {
|
||||
t.Fatalf("failed to start %s: %v", cmd, err)
|
||||
}
|
||||
|
||||
t.Cleanup(func() {
|
||||
cmdInstance.Process.Kill()
|
||||
cmdInstance.Wait()
|
||||
|
||||
if t.Failed() || testing.Verbose() {
|
||||
t.Logf("=== %s output ===", cmd)
|
||||
if stdout.Len() > 0 {
|
||||
t.Logf("stdout:\n%s", strings.TrimSpace(stdout.String()))
|
||||
}
|
||||
if stderr.Len() > 0 {
|
||||
t.Logf("stderr:\n%s", strings.TrimSpace(stderr.String()))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+6
-3
@@ -53,6 +53,9 @@ func (c *Client) registerRFC(ctx context.Context, acct *Account, prompt func(tos
|
||||
Contact: acct.Contact,
|
||||
}
|
||||
if c.dir.Terms != "" {
|
||||
if prompt == nil {
|
||||
return nil, errors.New("acme: missing Manager.Prompt to accept server's terms of service")
|
||||
}
|
||||
req.TermsAgreed = prompt(c.dir.Terms)
|
||||
}
|
||||
|
||||
@@ -232,7 +235,7 @@ func (c *Client) AuthorizeOrder(ctx context.Context, id []AuthzID, opt ...OrderO
|
||||
return responseOrder(res)
|
||||
}
|
||||
|
||||
// GetOrder retrives an order identified by the given URL.
|
||||
// GetOrder retrieves an order identified by the given URL.
|
||||
// For orders created with AuthorizeOrder, the url value is Order.URI.
|
||||
//
|
||||
// If a caller needs to poll an order until its status is final,
|
||||
@@ -272,7 +275,7 @@ func (c *Client) WaitOrder(ctx context.Context, url string) (*Order, error) {
|
||||
case err != nil:
|
||||
// Skip and retry.
|
||||
case o.Status == StatusInvalid:
|
||||
return nil, &OrderError{OrderURL: o.URI, Status: o.Status}
|
||||
return nil, &OrderError{OrderURL: o.URI, Status: o.Status, Problem: o.Error}
|
||||
case o.Status == StatusReady || o.Status == StatusValid:
|
||||
return o, nil
|
||||
}
|
||||
@@ -369,7 +372,7 @@ func (c *Client) CreateOrderCert(ctx context.Context, url string, csr []byte, bu
|
||||
}
|
||||
// The only acceptable status post finalize and WaitOrder is "valid".
|
||||
if o.Status != StatusValid {
|
||||
return nil, "", &OrderError{OrderURL: o.URI, Status: o.Status}
|
||||
return nil, "", &OrderError{OrderURL: o.URI, Status: o.Status, Problem: o.Error}
|
||||
}
|
||||
crt, err := c.fetchCertRFC(ctx, o.CertURL, bundle)
|
||||
return crt, o.CertURL, err
|
||||
|
||||
+16
-3
@@ -885,11 +885,17 @@ func TestRFC_WaitOrderError(t *testing.T) {
|
||||
s.handle("/orders/1", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Location", s.url("/orders/1"))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
s := StatusPending
|
||||
if count > 0 {
|
||||
s = StatusInvalid
|
||||
// https://www.rfc-editor.org/rfc/rfc8555#section-7.3.3
|
||||
errorData := `{
|
||||
"type": "urn:ietf:params:acme:error:userActionRequired",
|
||||
"detail": "Terms of service have changed",
|
||||
"instance": "https://example.com/acme/agreement/?token=W8Ih3PswD-8"
|
||||
}`
|
||||
fmt.Fprintf(w, `{"status": %q, "error": %s}`, StatusInvalid, errorData)
|
||||
} else {
|
||||
fmt.Fprintf(w, `{"status": %q}`, StatusPending)
|
||||
}
|
||||
fmt.Fprintf(w, `{"status": %q}`, s)
|
||||
count++
|
||||
})
|
||||
s.start()
|
||||
@@ -910,6 +916,13 @@ func TestRFC_WaitOrderError(t *testing.T) {
|
||||
if e.Status != StatusInvalid {
|
||||
t.Errorf("e.Status = %q; want %q", e.Status, StatusInvalid)
|
||||
}
|
||||
if e.Problem == nil {
|
||||
t.Errorf("e.Problem = nil")
|
||||
}
|
||||
expectedProbType := "urn:ietf:params:acme:error:userActionRequired"
|
||||
if e.Problem.ProblemType != expectedProbType {
|
||||
t.Errorf("e.Problem.ProblemType = %q; want %q", e.Problem.ProblemType, expectedProbType)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRFC_CreateOrderCert(t *testing.T) {
|
||||
|
||||
+9
-2
@@ -154,17 +154,24 @@ func (a *AuthorizationError) Error() string {
|
||||
|
||||
// OrderError is returned from Client's order related methods.
|
||||
// It indicates the order is unusable and the clients should start over with
|
||||
// AuthorizeOrder.
|
||||
// AuthorizeOrder. A Problem description may be provided with details on
|
||||
// what caused the order to become unusable.
|
||||
//
|
||||
// The clients can still fetch the order object from CA using GetOrder
|
||||
// to inspect its state.
|
||||
type OrderError struct {
|
||||
OrderURL string
|
||||
Status string
|
||||
// Problem is the error that occurred while processing the order.
|
||||
Problem *Error
|
||||
}
|
||||
|
||||
func (oe *OrderError) Error() string {
|
||||
return fmt.Sprintf("acme: order %s status: %s", oe.OrderURL, oe.Status)
|
||||
str := fmt.Sprintf("acme: order %s status: %s", oe.OrderURL, oe.Status)
|
||||
if oe.Problem != nil {
|
||||
str += fmt.Sprintf("; problem: %s", oe.Problem)
|
||||
}
|
||||
return str
|
||||
}
|
||||
|
||||
// RateLimit reports whether err represents a rate limit error and
|
||||
|
||||
@@ -217,3 +217,19 @@ func TestErrorStringerWithSubproblems(t *testing.T) {
|
||||
t.Errorf("Unexpected error string: wanted %q, got %q", expectedStr, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrderErrorProblem(t *testing.T) {
|
||||
oe := &OrderError{
|
||||
OrderURL: "url",
|
||||
Status: "invalid",
|
||||
Problem: &Error{
|
||||
StatusCode: 400,
|
||||
ProblemType: "type",
|
||||
Detail: "detail",
|
||||
},
|
||||
}
|
||||
want := "acme: order url status: invalid; problem: 400 type: detail"
|
||||
if got := oe.Error(); got != want {
|
||||
t.Errorf("oe.Error() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
+11
-7
@@ -6,7 +6,7 @@
|
||||
// Argon2 was selected as the winner of the Password Hashing Competition and can
|
||||
// be used to derive cryptographic keys from passwords.
|
||||
//
|
||||
// For a detailed specification of Argon2 see [1].
|
||||
// For a detailed specification of Argon2 see [argon2-specs.pdf].
|
||||
//
|
||||
// If you aren't sure which function you need, use Argon2id (IDKey) and
|
||||
// the parameter recommendations for your scenario.
|
||||
@@ -17,7 +17,7 @@
|
||||
// It uses data-independent memory access, which is preferred for password
|
||||
// hashing and password-based key derivation. Argon2i requires more passes over
|
||||
// memory than Argon2id to protect from trade-off attacks. The recommended
|
||||
// parameters (taken from [2]) for non-interactive operations are time=3 and to
|
||||
// parameters (taken from [RFC 9106 Section 7.3]) for non-interactive operations are time=3 and to
|
||||
// use the maximum available memory.
|
||||
//
|
||||
// # Argon2id
|
||||
@@ -27,11 +27,11 @@
|
||||
// half of the first iteration over the memory and data-dependent memory access
|
||||
// for the rest. Argon2id is side-channel resistant and provides better brute-
|
||||
// force cost savings due to time-memory tradeoffs than Argon2i. The recommended
|
||||
// parameters for non-interactive operations (taken from [2]) are time=1 and to
|
||||
// parameters for non-interactive operations (taken from [RFC 9106 Section 7.3]) are time=1 and to
|
||||
// use the maximum available memory.
|
||||
//
|
||||
// [1] https://github.com/P-H-C/phc-winner-argon2/blob/master/argon2-specs.pdf
|
||||
// [2] https://tools.ietf.org/html/draft-irtf-cfrg-argon2-03#section-9.3
|
||||
// [argon2-specs.pdf]: https://github.com/P-H-C/phc-winner-argon2/blob/master/argon2-specs.pdf
|
||||
// [RFC 9106 Section 7.3]: https://www.rfc-editor.org/rfc/rfc9106.html#section-7.3
|
||||
package argon2
|
||||
|
||||
import (
|
||||
@@ -59,7 +59,7 @@ const (
|
||||
//
|
||||
// key := argon2.Key([]byte("some password"), salt, 3, 32*1024, 4, 32)
|
||||
//
|
||||
// The draft RFC recommends[2] time=3, and memory=32*1024 is a sensible number.
|
||||
// [RFC 9106 Section 7.3] recommends time=3, and memory=32*1024 as a sensible number.
|
||||
// If using that amount of memory (32 MB) is not possible in some contexts then
|
||||
// the time parameter can be increased to compensate.
|
||||
//
|
||||
@@ -69,6 +69,8 @@ const (
|
||||
// adjusted to the number of available CPUs. The cost parameters should be
|
||||
// increased as memory latency and CPU parallelism increases. Remember to get a
|
||||
// good random salt.
|
||||
//
|
||||
// [RFC 9106 Section 7.3]: https://www.rfc-editor.org/rfc/rfc9106.html#section-7.3
|
||||
func Key(password, salt []byte, time, memory uint32, threads uint8, keyLen uint32) []byte {
|
||||
return deriveKey(argon2i, password, salt, nil, nil, time, memory, threads, keyLen)
|
||||
}
|
||||
@@ -83,7 +85,7 @@ func Key(password, salt []byte, time, memory uint32, threads uint8, keyLen uint3
|
||||
//
|
||||
// key := argon2.IDKey([]byte("some password"), salt, 1, 64*1024, 4, 32)
|
||||
//
|
||||
// The draft RFC recommends[2] time=1, and memory=64*1024 is a sensible number.
|
||||
// [RFC 9106 Section 7.3] recommends time=1, and memory=64*1024 as a sensible number.
|
||||
// If using that amount of memory (64 MB) is not possible in some contexts then
|
||||
// the time parameter can be increased to compensate.
|
||||
//
|
||||
@@ -93,6 +95,8 @@ func Key(password, salt []byte, time, memory uint32, threads uint8, keyLen uint3
|
||||
// adjusted to the numbers of available CPUs. The cost parameters should be
|
||||
// increased as memory latency and CPU parallelism increases. Remember to get a
|
||||
// good random salt.
|
||||
//
|
||||
// [RFC 9106 Section 7.3]: https://www.rfc-editor.org/rfc/rfc9106.html#section-7.3
|
||||
func IDKey(password, salt []byte, time, memory uint32, threads uint8, keyLen uint32) []byte {
|
||||
return deriveKey(argon2id, password, salt, nil, nil, time, memory, threads, keyLen)
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ hash.XOF = (*xof)(nil)
|
||||
|
||||
func fromHex(s string) []byte {
|
||||
b, err := hex.DecodeString(s)
|
||||
if err != nil {
|
||||
|
||||
@@ -29,7 +29,7 @@ loop:
|
||||
MOVD $NUM_ROUNDS, R21
|
||||
VLD1 (R11), [V30.S4, V31.S4]
|
||||
|
||||
// load contants
|
||||
// load constants
|
||||
// VLD4R (R10), [V0.S4, V1.S4, V2.S4, V3.S4]
|
||||
WORD $0x4D60E940
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -38,6 +38,9 @@ type chacha20poly1305 struct {
|
||||
|
||||
// New returns a ChaCha20-Poly1305 AEAD that uses the given 256-bit key.
|
||||
func New(key []byte) (cipher.AEAD, error) {
|
||||
if fips140Enforced() {
|
||||
return nil, errors.New("chacha20poly1305: use of ChaCha20Poly1305 is not allowed in FIPS 140-only mode")
|
||||
}
|
||||
if len(key) != KeySize {
|
||||
return nil, errors.New("chacha20poly1305: bad key length")
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ func chacha20Poly1305Open(dst []byte, key []uint32, src, ad []byte) bool
|
||||
func chacha20Poly1305Seal(dst []byte, key []uint32, src, ad []byte)
|
||||
|
||||
var (
|
||||
useAVX2 = cpu.X86.HasAVX2 && cpu.X86.HasBMI2
|
||||
useAVX2 = cpu.X86.HasSSSE3 && cpu.X86.HasAVX2 && cpu.X86.HasBMI2
|
||||
)
|
||||
|
||||
// setupState writes a ChaCha20 input matrix to state. See
|
||||
@@ -47,7 +47,7 @@ func setupState(state *[16]uint32, key *[32]byte, nonce []byte) {
|
||||
}
|
||||
|
||||
func (c *chacha20poly1305) seal(dst, nonce, plaintext, additionalData []byte) []byte {
|
||||
if !cpu.X86.HasSSSE3 {
|
||||
if !useAVX2 {
|
||||
return c.sealGeneric(dst, nonce, plaintext, additionalData)
|
||||
}
|
||||
|
||||
@@ -56,14 +56,17 @@ func (c *chacha20poly1305) seal(dst, nonce, plaintext, additionalData []byte) []
|
||||
|
||||
ret, out := sliceForAppend(dst, len(plaintext)+16)
|
||||
if alias.InexactOverlap(out, plaintext) {
|
||||
panic("chacha20poly1305: invalid buffer overlap")
|
||||
panic("chacha20poly1305: invalid buffer overlap of output and input")
|
||||
}
|
||||
if alias.AnyOverlap(out, additionalData) {
|
||||
panic("chacha20poly1305: invalid buffer overlap of output and additional data")
|
||||
}
|
||||
chacha20Poly1305Seal(out[:], state[:], plaintext, additionalData)
|
||||
return ret
|
||||
}
|
||||
|
||||
func (c *chacha20poly1305) open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
|
||||
if !cpu.X86.HasSSSE3 {
|
||||
if !useAVX2 {
|
||||
return c.openGeneric(dst, nonce, ciphertext, additionalData)
|
||||
}
|
||||
|
||||
@@ -73,7 +76,10 @@ func (c *chacha20poly1305) open(dst, nonce, ciphertext, additionalData []byte) (
|
||||
ciphertext = ciphertext[:len(ciphertext)-16]
|
||||
ret, out := sliceForAppend(dst, len(ciphertext))
|
||||
if alias.InexactOverlap(out, ciphertext) {
|
||||
panic("chacha20poly1305: invalid buffer overlap")
|
||||
panic("chacha20poly1305: invalid buffer overlap of output and input")
|
||||
}
|
||||
if alias.AnyOverlap(out, additionalData) {
|
||||
panic("chacha20poly1305: invalid buffer overlap of output and additional data")
|
||||
}
|
||||
if !chacha20Poly1305Open(out, state[:], ciphertext, additionalData) {
|
||||
for i := range out {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -31,7 +31,10 @@ func (c *chacha20poly1305) sealGeneric(dst, nonce, plaintext, additionalData []b
|
||||
ret, out := sliceForAppend(dst, len(plaintext)+poly1305.TagSize)
|
||||
ciphertext, tag := out[:len(plaintext)], out[len(plaintext):]
|
||||
if alias.InexactOverlap(out, plaintext) {
|
||||
panic("chacha20poly1305: invalid buffer overlap")
|
||||
panic("chacha20poly1305: invalid buffer overlap of output and input")
|
||||
}
|
||||
if alias.AnyOverlap(out, additionalData) {
|
||||
panic("chacha20poly1305: invalid buffer overlap of output and additional data")
|
||||
}
|
||||
|
||||
var polyKey [32]byte
|
||||
@@ -67,7 +70,10 @@ func (c *chacha20poly1305) openGeneric(dst, nonce, ciphertext, additionalData []
|
||||
|
||||
ret, out := sliceForAppend(dst, len(ciphertext))
|
||||
if alias.InexactOverlap(out, ciphertext) {
|
||||
panic("chacha20poly1305: invalid buffer overlap")
|
||||
panic("chacha20poly1305: invalid buffer overlap of output and input")
|
||||
}
|
||||
if alias.AnyOverlap(out, additionalData) {
|
||||
panic("chacha20poly1305: invalid buffer overlap of output and additional data")
|
||||
}
|
||||
if !p.Verify(tag) {
|
||||
for i := range out {
|
||||
|
||||
@@ -153,7 +153,7 @@ func TestRandom(t *testing.T) {
|
||||
t.Run("X", func(t *testing.T) { f(t, NonceSizeX) })
|
||||
}
|
||||
|
||||
func benchamarkChaCha20Poly1305Seal(b *testing.B, buf []byte, nonceSize int) {
|
||||
func benchmarkChaCha20Poly1305Seal(b *testing.B, buf []byte, nonceSize int) {
|
||||
b.ReportAllocs()
|
||||
b.SetBytes(int64(len(buf)))
|
||||
|
||||
@@ -176,7 +176,7 @@ func benchamarkChaCha20Poly1305Seal(b *testing.B, buf []byte, nonceSize int) {
|
||||
}
|
||||
}
|
||||
|
||||
func benchamarkChaCha20Poly1305Open(b *testing.B, buf []byte, nonceSize int) {
|
||||
func benchmarkChaCha20Poly1305Open(b *testing.B, buf []byte, nonceSize int) {
|
||||
b.ReportAllocs()
|
||||
b.SetBytes(int64(len(buf)))
|
||||
|
||||
@@ -204,17 +204,17 @@ func benchamarkChaCha20Poly1305Open(b *testing.B, buf []byte, nonceSize int) {
|
||||
func BenchmarkChacha20Poly1305(b *testing.B) {
|
||||
for _, length := range []int{64, 1350, 8 * 1024} {
|
||||
b.Run("Open-"+strconv.Itoa(length), func(b *testing.B) {
|
||||
benchamarkChaCha20Poly1305Open(b, make([]byte, length), NonceSize)
|
||||
benchmarkChaCha20Poly1305Open(b, make([]byte, length), NonceSize)
|
||||
})
|
||||
b.Run("Seal-"+strconv.Itoa(length), func(b *testing.B) {
|
||||
benchamarkChaCha20Poly1305Seal(b, make([]byte, length), NonceSize)
|
||||
benchmarkChaCha20Poly1305Seal(b, make([]byte, length), NonceSize)
|
||||
})
|
||||
|
||||
b.Run("Open-"+strconv.Itoa(length)+"-X", func(b *testing.B) {
|
||||
benchamarkChaCha20Poly1305Open(b, make([]byte, length), NonceSizeX)
|
||||
benchmarkChaCha20Poly1305Open(b, make([]byte, length), NonceSizeX)
|
||||
})
|
||||
b.Run("Seal-"+strconv.Itoa(length)+"-X", func(b *testing.B) {
|
||||
benchamarkChaCha20Poly1305Seal(b, make([]byte, length), NonceSizeX)
|
||||
benchmarkChaCha20Poly1305Seal(b, make([]byte, length), NonceSizeX)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,10 +2,8 @@
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build go1.25
|
||||
//go:build !go1.26
|
||||
|
||||
package blake2b
|
||||
package chacha20poly1305
|
||||
|
||||
import "hash"
|
||||
|
||||
var _ hash.XOF = (*xof)(nil)
|
||||
func fips140Enforced() bool { return false }
|
||||
@@ -0,0 +1,11 @@
|
||||
// Copyright 2025 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build go1.26
|
||||
|
||||
package chacha20poly1305
|
||||
|
||||
import "crypto/fips140"
|
||||
|
||||
func fips140Enforced() bool { return fips140.Enforced() }
|
||||
@@ -22,6 +22,9 @@ type xchacha20poly1305 struct {
|
||||
// preferred when nonce uniqueness cannot be trivially ensured, or whenever
|
||||
// nonces are randomly generated.
|
||||
func NewX(key []byte) (cipher.AEAD, error) {
|
||||
if fips140Enforced() {
|
||||
return nil, errors.New("chacha20poly1305: use of ChaCha20Poly1305 is not allowed in FIPS 140-only mode")
|
||||
}
|
||||
if len(key) != KeySize {
|
||||
return nil, errors.New("chacha20poly1305: bad key length")
|
||||
}
|
||||
|
||||
@@ -3,11 +3,14 @@
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package curve25519 provides an implementation of the X25519 function, which
|
||||
// performs scalar multiplication on the elliptic curve known as Curve25519.
|
||||
// See RFC 7748.
|
||||
// performs scalar multiplication on the elliptic curve known as Curve25519
|
||||
// according to [RFC 7748].
|
||||
//
|
||||
// This package is a wrapper for the X25519 implementation
|
||||
// in the crypto/ecdh package.
|
||||
// The curve25519 package is a wrapper for the X25519 implementation in the
|
||||
// crypto/ecdh package. It is [frozen] and is not accepting new features.
|
||||
//
|
||||
// [RFC 7748]: https://datatracker.ietf.org/doc/html/rfc7748
|
||||
// [frozen]: https://go.dev/wiki/Frozen
|
||||
package curve25519
|
||||
|
||||
import "crypto/ecdh"
|
||||
@@ -36,7 +39,7 @@ func ScalarBaseMult(dst, scalar *[32]byte) {
|
||||
curve := ecdh.X25519()
|
||||
priv, err := curve.NewPrivateKey(scalar[:])
|
||||
if err != nil {
|
||||
panic("curve25519: internal error: scalarBaseMult was not 32 bytes")
|
||||
panic("curve25519: " + err.Error())
|
||||
}
|
||||
copy(dst[:], priv.PublicKey().Bytes())
|
||||
}
|
||||
|
||||
+7
-4
@@ -2,16 +2,19 @@
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package ed25519 implements the Ed25519 signature algorithm. See
|
||||
// https://ed25519.cr.yp.to/.
|
||||
// Package ed25519 implements the Ed25519 signature algorithm.
|
||||
//
|
||||
// These functions are also compatible with the “Ed25519” function defined in
|
||||
// RFC 8032. However, unlike RFC 8032's formulation, this package's private key
|
||||
// [RFC 8032]. However, unlike RFC 8032's formulation, this package's private key
|
||||
// representation includes a public key suffix to make multiple signing
|
||||
// operations with the same key more efficient. This package refers to the RFC
|
||||
// 8032 private key as the “seed”.
|
||||
//
|
||||
// This package is a wrapper around the standard library crypto/ed25519 package.
|
||||
// The ed25519 package is a wrapper for the Ed25519 implementation in the
|
||||
// crypto/ed25519 package. It is [frozen] and is not accepting new features.
|
||||
//
|
||||
// [RFC 8032]: https://datatracker.ietf.org/doc/html/rfc8032
|
||||
// [frozen]: https://go.dev/wiki/Frozen
|
||||
package ed25519
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
module golang.org/x/crypto
|
||||
|
||||
go 1.23.0
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
golang.org/x/net v0.41.0 // tagx:ignore
|
||||
golang.org/x/sys v0.34.0
|
||||
golang.org/x/term v0.33.0
|
||||
golang.org/x/net v0.55.0 // tagx:ignore
|
||||
golang.org/x/sys v0.46.0
|
||||
golang.org/x/term v0.44.0
|
||||
)
|
||||
|
||||
require golang.org/x/text v0.27.0 // indirect
|
||||
require golang.org/x/text v0.38.0 // indirect
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw=
|
||||
golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA=
|
||||
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
|
||||
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=
|
||||
golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=
|
||||
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
|
||||
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
|
||||
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
|
||||
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
|
||||
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
|
||||
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
|
||||
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
|
||||
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
|
||||
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
|
||||
|
||||
+13
-8
@@ -11,6 +11,7 @@
|
||||
package hkdf
|
||||
|
||||
import (
|
||||
"crypto/hkdf"
|
||||
"crypto/hmac"
|
||||
"errors"
|
||||
"hash"
|
||||
@@ -24,15 +25,19 @@ import (
|
||||
// Expand invocations and different context values. Most common scenarios,
|
||||
// including the generation of multiple keys, should use New instead.
|
||||
func Extract(hash func() hash.Hash, secret, salt []byte) []byte {
|
||||
if salt == nil {
|
||||
salt = make([]byte, hash().Size())
|
||||
// Use the stdlib Extract, which disables FIPS 140 enforcement of the HMAC
|
||||
// key (which in HKDF is the salt). The only possible error is FIPS 140
|
||||
// enforcement of the hash, which had to panic under this API anyway. We
|
||||
// don't use the stdlib Expand, because it switched to returning a []byte
|
||||
// instead of an io.Reader, and Expand uses the HMAC key as a key.
|
||||
out, err := hkdf.Extract(hash, secret, salt)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
extractor := hmac.New(hash, salt)
|
||||
extractor.Write(secret)
|
||||
return extractor.Sum(nil)
|
||||
return out
|
||||
}
|
||||
|
||||
type hkdf struct {
|
||||
type hkdfReader struct {
|
||||
expander hash.Hash
|
||||
size int
|
||||
|
||||
@@ -43,7 +48,7 @@ type hkdf struct {
|
||||
buf []byte
|
||||
}
|
||||
|
||||
func (f *hkdf) Read(p []byte) (int, error) {
|
||||
func (f *hkdfReader) Read(p []byte) (int, error) {
|
||||
// Check whether enough data can be generated
|
||||
need := len(p)
|
||||
remains := len(f.buf) + int(255-f.counter+1)*f.size
|
||||
@@ -84,7 +89,7 @@ func (f *hkdf) Read(p []byte) (int, error) {
|
||||
// 3.3. Most common scenarios will want to use New instead.
|
||||
func Expand(hash func() hash.Hash, pseudorandomKey, info []byte) io.Reader {
|
||||
expander := hmac.New(hash, pseudorandomKey)
|
||||
return &hkdf{expander, expander.Size(), info, 1, nil, nil}
|
||||
return &hkdfReader{expander, expander.Size(), info, 1, nil, nil}
|
||||
}
|
||||
|
||||
// New returns a Reader, from which keys can be read, using the given hash,
|
||||
|
||||
@@ -141,7 +141,7 @@ func TestRsaPss(t *testing.T) {
|
||||
}
|
||||
// Run all the tests twice: the first time with the salt length
|
||||
// as PSSSaltLengthAuto, and the second time with the salt length
|
||||
// explictily set to tg.SLen.
|
||||
// explicitly set to tg.SLen.
|
||||
for i := 0; i < 2; i++ {
|
||||
for _, sig := range tg.Tests {
|
||||
h.Reset()
|
||||
|
||||
+10
-19
@@ -2,25 +2,16 @@
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
/*
|
||||
Package auth authenticates a message using a secret key.
|
||||
|
||||
The Sum function, viewed as a function of the message for a uniform random
|
||||
key, is designed to meet the standard notion of unforgeability. This means
|
||||
that an attacker cannot find authenticators for any messages not authenticated
|
||||
by the sender, even if the attacker has adaptively influenced the messages
|
||||
authenticated by the sender. For a formal definition see, e.g., Section 2.4
|
||||
of Bellare, Kilian, and Rogaway, "The security of the cipher block chaining
|
||||
message authentication code," Journal of Computer and System Sciences 61 (2000),
|
||||
362–399; http://www-cse.ucsd.edu/~mihir/papers/cbc.html.
|
||||
|
||||
auth does not make any promises regarding "strong" unforgeability; perhaps
|
||||
one valid authenticator can be converted into another valid authenticator for
|
||||
the same message. NaCl also does not make any promises regarding "truncated
|
||||
unforgeability."
|
||||
|
||||
This package is interoperable with NaCl: https://nacl.cr.yp.to/auth.html.
|
||||
*/
|
||||
// Package auth authenticates a message using a secret key.
|
||||
//
|
||||
// This package is interoperable with [NaCl].
|
||||
//
|
||||
// The auth package is essentially a wrapper for HMAC-SHA-512 (implemented by
|
||||
// crypto/hmac and crypto/sha512), truncated to 32 bytes. It is [frozen] and is
|
||||
// not accepting new features.
|
||||
//
|
||||
// [NaCl]: https://nacl.cr.yp.to/auth.html
|
||||
// [frozen]: https://go.dev/wiki/Frozen
|
||||
package auth
|
||||
|
||||
import (
|
||||
|
||||
@@ -114,7 +114,7 @@ func TestSealOpenAnonymous(t *testing.T) {
|
||||
t.Fatal("expected out to be unchanged")
|
||||
}
|
||||
if !bytes.HasPrefix(box, orig) {
|
||||
t.Fatal("expected out to be coppied to returned slice")
|
||||
t.Fatal("expected out to be copied to returned slice")
|
||||
}
|
||||
_, ok = OpenAnonymous(nil, box[len(out):], publicKey, privateKey)
|
||||
if !ok {
|
||||
|
||||
+8
-13
@@ -4,20 +4,15 @@
|
||||
|
||||
// Package sign signs small messages using public-key cryptography.
|
||||
//
|
||||
// Sign uses Ed25519 to sign messages. The length of messages is not hidden.
|
||||
// Messages should be small because:
|
||||
// 1. The whole message needs to be held in memory to be processed.
|
||||
// 2. Using large messages pressures implementations on small machines to process
|
||||
// plaintext without verifying the signature. This is very dangerous, and this API
|
||||
// discourages it, but a protocol that uses excessive message sizes might present
|
||||
// some implementations with no other choice.
|
||||
// 3. Performance may be improved by working with messages that fit into data caches.
|
||||
// Thus large amounts of data should be chunked so that each message is small.
|
||||
// This package is interoperable with [libsodium], as well as [TweetNaCl].
|
||||
//
|
||||
// This package is not interoperable with the current release of NaCl
|
||||
// (https://nacl.cr.yp.to/sign.html), which does not support Ed25519 yet. However,
|
||||
// it is compatible with the NaCl fork libsodium (https://www.libsodium.org), as well
|
||||
// as TweetNaCl (https://tweetnacl.cr.yp.to/).
|
||||
// The sign package is essentially a wrapper for the Ed25519 signature
|
||||
// algorithm (implemented by crypto/ed25519). It is [frozen] and is not accepting
|
||||
// new features.
|
||||
//
|
||||
// [libsodium]: https://libsodium.gitbook.io/doc/public-key_cryptography/public-key_signatures
|
||||
// [TweetNaCl]: https://tweetnacl.cr.yp.to/
|
||||
// [frozen]: https://go.dev/wiki/Frozen
|
||||
package sign
|
||||
|
||||
import (
|
||||
|
||||
@@ -69,6 +69,6 @@ func TestGenerateSignOpen(t *testing.T) {
|
||||
}
|
||||
|
||||
if !bytes.Equal(message, testMessage) {
|
||||
t.Fatalf("verified message does not match signed messge, got\n%x\n, expected\n%x", message, testMessage)
|
||||
t.Fatalf("verified message does not match signed message, got\n%x\n, expected\n%x", message, testMessage)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ func TestOpaqueParseReason(t *testing.T) {
|
||||
const expectedBad = 3
|
||||
// Test post-conditions, make sure we actually parsed packets as expected.
|
||||
if badPackets != expectedBad {
|
||||
t.Errorf("unexpected # unparseable packets: %d (want %d)", badPackets, expectedBad)
|
||||
t.Errorf("unexpected # unparsable packets: %d (want %d)", badPackets, expectedBad)
|
||||
}
|
||||
if uid == nil {
|
||||
t.Errorf("failed to find expected UID in unsupported keyring")
|
||||
|
||||
+1
-1
@@ -53,7 +53,7 @@ func (c *Config) hash() crypto.Hash {
|
||||
|
||||
func (c *Config) encodedCount() uint8 {
|
||||
if c == nil || c.S2KCount == 0 {
|
||||
return 96 // The common case. Correspoding to 65536
|
||||
return 96 // The common case. Corresponding to 65536
|
||||
}
|
||||
|
||||
i := c.S2KCount
|
||||
|
||||
@@ -8,6 +8,10 @@
|
||||
// The version of OTR implemented by this package has been deprecated
|
||||
// (https://bugs.otr.im/lib/libotr/issues/140). An implementation of OTRv3 is
|
||||
// available at https://github.com/coyim/otr3.
|
||||
//
|
||||
// The otr package is [frozen] and is not accepting new features.
|
||||
//
|
||||
// [frozen]: https://go.dev/wiki/Frozen
|
||||
package otr
|
||||
|
||||
import (
|
||||
|
||||
+3
-3
@@ -75,8 +75,8 @@ const libOTRPrivateKey = `(privkeys
|
||||
(account
|
||||
(name "foo@example.com")
|
||||
(protocol prpl-jabber)
|
||||
(private-key
|
||||
(dsa
|
||||
(private-key
|
||||
(dsa
|
||||
(p #00FC07ABCF0DC916AFF6E9AE47BEF60C7AB9B4D6B2469E436630E36F8A489BE812486A09F30B71224508654940A835301ACC525A4FF133FC152CC53DCC59D65C30A54F1993FE13FE63E5823D4C746DB21B90F9B9C00B49EC7404AB1D929BA7FBA12F2E45C6E0A651689750E8528AB8C031D3561FECEE72EBB4A090D450A9B7A857#)
|
||||
(q #00997BD266EF7B1F60A5C23F3A741F2AEFD07A2081#)
|
||||
(g #535E360E8A95EBA46A4F7DE50AD6E9B2A6DB785A66B64EB9F20338D2A3E8FB0E94725848F1AA6CC567CB83A1CC517EC806F2E92EAE71457E80B2210A189B91250779434B41FC8A8873F6DB94BEA7D177F5D59E7E114EE10A49CFD9CEF88AE43387023B672927BA74B04EB6BBB5E57597766A2F9CE3857D7ACE3E1E3BC1FC6F26#)
|
||||
@@ -402,7 +402,7 @@ func TestAgainstLibOTR(t *testing.T) {
|
||||
// This test requires otr.c.test to be built as /tmp/a.out.
|
||||
// If enabled, this tests runs forever performing OTR handshakes in a
|
||||
// loop.
|
||||
return
|
||||
t.Skip("This test requires otr.c.test to be built as /tmp/a.out")
|
||||
|
||||
alicePrivateKey, _ := hex.DecodeString(alicePrivateKeyHex)
|
||||
var alice Conversation
|
||||
|
||||
+13
-60
@@ -2,24 +2,17 @@
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
/*
|
||||
Package pbkdf2 implements the key derivation function PBKDF2 as defined in RFC
|
||||
2898 / PKCS #5 v2.0.
|
||||
|
||||
A key derivation function is useful when encrypting data based on a password
|
||||
or any other not-fully-random data. It uses a pseudorandom function to derive
|
||||
a secure encryption key based on the password.
|
||||
|
||||
While v2.0 of the standard defines only one pseudorandom function to use,
|
||||
HMAC-SHA1, the drafted v2.1 specification allows use of all five FIPS Approved
|
||||
Hash Functions SHA-1, SHA-224, SHA-256, SHA-384 and SHA-512 for HMAC. To
|
||||
choose, you can pass the `New` functions from the different SHA packages to
|
||||
pbkdf2.Key.
|
||||
*/
|
||||
// Package pbkdf2 implements the key derivation function PBKDF2 as defined in
|
||||
// RFC 8018 (PKCS #5 v2.1).
|
||||
//
|
||||
// This package is a wrapper for the PBKDF2 implementation in the
|
||||
// [crypto/pbkdf2] package. It is [frozen] and is not accepting new features.
|
||||
//
|
||||
// [frozen]: https://go.dev/wiki/Frozen
|
||||
package pbkdf2
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/pbkdf2"
|
||||
"hash"
|
||||
)
|
||||
|
||||
@@ -27,51 +20,11 @@ import (
|
||||
// []byte of length keylen that can be used as cryptographic key. The key is
|
||||
// derived based on the method described as PBKDF2 with the HMAC variant using
|
||||
// the supplied hash function.
|
||||
//
|
||||
// For example, to use a HMAC-SHA-1 based PBKDF2 key derivation function, you
|
||||
// can get a derived key for e.g. AES-256 (which needs a 32-byte key) by
|
||||
// doing:
|
||||
//
|
||||
// dk := pbkdf2.Key([]byte("some password"), salt, 4096, 32, sha1.New)
|
||||
//
|
||||
// Remember to get a good random salt. At least 8 bytes is recommended by the
|
||||
// RFC.
|
||||
//
|
||||
// Using a higher iteration count will increase the cost of an exhaustive
|
||||
// search but will also make derivation proportionally slower.
|
||||
func Key(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte {
|
||||
prf := hmac.New(h, password)
|
||||
hashLen := prf.Size()
|
||||
numBlocks := (keyLen + hashLen - 1) / hashLen
|
||||
|
||||
var buf [4]byte
|
||||
dk := make([]byte, 0, numBlocks*hashLen)
|
||||
U := make([]byte, hashLen)
|
||||
for block := 1; block <= numBlocks; block++ {
|
||||
// N.B.: || means concatenation, ^ means XOR
|
||||
// for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter
|
||||
// U_1 = PRF(password, salt || uint(i))
|
||||
prf.Reset()
|
||||
prf.Write(salt)
|
||||
buf[0] = byte(block >> 24)
|
||||
buf[1] = byte(block >> 16)
|
||||
buf[2] = byte(block >> 8)
|
||||
buf[3] = byte(block)
|
||||
prf.Write(buf[:4])
|
||||
dk = prf.Sum(dk)
|
||||
T := dk[len(dk)-hashLen:]
|
||||
copy(U, T)
|
||||
|
||||
// U_n = PRF(password, U_(n-1))
|
||||
for n := 2; n <= iter; n++ {
|
||||
prf.Reset()
|
||||
prf.Write(U)
|
||||
U = U[:0]
|
||||
U = prf.Sum(U)
|
||||
for x := range U {
|
||||
T[x] ^= U[x]
|
||||
}
|
||||
}
|
||||
out, err := pbkdf2.Key(h, string(password), salt, iter, keyLen)
|
||||
if err != nil {
|
||||
// FIPS 140 enforcement, or an invalid key length.
|
||||
panic(err)
|
||||
}
|
||||
return dk[:keyLen]
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -80,6 +80,10 @@ func pbDecrypterFor(algorithm pkix.AlgorithmIdentifier, password []byte) (cipher
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if params.Iterations < 0 || params.Iterations > maxIterations {
|
||||
return nil, 0, NotImplementedError("iteration count is invalid or too high")
|
||||
}
|
||||
|
||||
key := cipherType.deriveKey(params.Salt, password, params.Iterations)
|
||||
iv := cipherType.deriveIV(params.Salt, password, params.Iterations)
|
||||
|
||||
|
||||
@@ -13,6 +13,46 @@ import (
|
||||
|
||||
var sha1WithTripleDES = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 3})
|
||||
|
||||
func TestPbDecrypterForIterationLimit(t *testing.T) {
|
||||
pass, _ := bmpString("Sesame open")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
iterations int
|
||||
wantErr bool
|
||||
}{
|
||||
{"at limit", maxIterations, false},
|
||||
{"over limit", maxIterations + 1, true},
|
||||
{"negative", -1, true},
|
||||
{"max int", 1<<31 - 1, true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
params, _ := asn1.Marshal(pbeParams{
|
||||
Salt: []byte{1, 2, 3, 4, 5, 6, 7, 8},
|
||||
Iterations: tt.iterations,
|
||||
})
|
||||
alg := pkix.AlgorithmIdentifier{
|
||||
Algorithm: sha1WithTripleDES,
|
||||
Parameters: asn1.RawValue{
|
||||
FullBytes: params,
|
||||
},
|
||||
}
|
||||
_, _, err := pbDecrypterFor(alg, pass)
|
||||
if tt.wantErr {
|
||||
if _, ok := err.(NotImplementedError); !ok {
|
||||
t.Errorf("iterations=%d: got %v, want NotImplementedError", tt.iterations, err)
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Errorf("iterations=%d: unexpected error: %v", tt.iterations, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPbDecrypterFor(t *testing.T) {
|
||||
params, _ := asn1.Marshal(pbeParams{
|
||||
Salt: []byte{1, 2, 3, 4, 5, 6, 7, 8},
|
||||
|
||||
@@ -27,11 +27,19 @@ var (
|
||||
oidSHA1 = asn1.ObjectIdentifier([]int{1, 3, 14, 3, 2, 26})
|
||||
)
|
||||
|
||||
// maxIterations is a safety limit to prevent CPU exhaustion from
|
||||
// crafted PKCS#12 files with unreasonable iteration counts.
|
||||
const maxIterations = 1 << 20 // ~1 million
|
||||
|
||||
func verifyMac(macData *macData, message, password []byte) error {
|
||||
if !macData.Mac.Algorithm.Algorithm.Equal(oidSHA1) {
|
||||
return NotImplementedError("unknown digest algorithm: " + macData.Mac.Algorithm.Algorithm.String())
|
||||
}
|
||||
|
||||
if macData.Iterations < 0 || macData.Iterations > maxIterations {
|
||||
return NotImplementedError("iteration count is invalid or too high")
|
||||
}
|
||||
|
||||
key := pbkdf(sha1Sum, 20, 64, macData.MacSalt, password, macData.Iterations, 3, 20)
|
||||
|
||||
mac := hmac.New(sha1.New, key)
|
||||
|
||||
@@ -5,10 +5,52 @@
|
||||
package pkcs12
|
||||
|
||||
import (
|
||||
"crypto/x509/pkix"
|
||||
"encoding/asn1"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestVerifyMacIterationLimit(t *testing.T) {
|
||||
password, _ := bmpString("Sesame open")
|
||||
message := []byte{11, 12, 13, 14, 15}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
iterations int
|
||||
wantErr bool
|
||||
}{
|
||||
{"at limit", maxIterations, false},
|
||||
{"over limit", maxIterations + 1, true},
|
||||
{"negative", -1, true},
|
||||
{"max int", 1<<31 - 1, true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
td := macData{
|
||||
Mac: digestInfo{
|
||||
Algorithm: pkix.AlgorithmIdentifier{
|
||||
Algorithm: oidSHA1,
|
||||
},
|
||||
Digest: nil, // will fail MAC check, but iteration check comes first
|
||||
},
|
||||
MacSalt: []byte{1, 2, 3, 4, 5, 6, 7, 8},
|
||||
Iterations: tt.iterations,
|
||||
}
|
||||
err := verifyMac(&td, message, password)
|
||||
if tt.wantErr {
|
||||
if _, ok := err.(NotImplementedError); !ok {
|
||||
t.Errorf("iterations=%d: got %v, want NotImplementedError", tt.iterations, err)
|
||||
}
|
||||
} else {
|
||||
if _, ok := err.(NotImplementedError); ok {
|
||||
t.Errorf("iterations=%d: got unexpected NotImplementedError", tt.iterations)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyMac(t *testing.T) {
|
||||
td := macData{
|
||||
Mac: digestInfo{
|
||||
|
||||
+9
-5
@@ -4,12 +4,16 @@
|
||||
|
||||
// Package pkcs12 implements some of PKCS#12.
|
||||
//
|
||||
// This implementation is distilled from https://tools.ietf.org/html/rfc7292
|
||||
// and referenced documents. It is intended for decoding P12/PFX-stored
|
||||
// certificates and keys for use with the crypto/tls package.
|
||||
// This implementation is distilled from [RFC 7292] and referenced documents.
|
||||
// It is intended for decoding P12/PFX-stored certificates and keys for use
|
||||
// with the crypto/tls package.
|
||||
//
|
||||
// This package is frozen. If it's missing functionality you need, consider
|
||||
// an alternative like software.sslmate.com/src/go-pkcs12.
|
||||
// The pkcs12 package is [frozen] and is not accepting new features.
|
||||
// If it's missing functionality you need, consider an alternative like
|
||||
// software.sslmate.com/src/go-pkcs12.
|
||||
//
|
||||
// [RFC 7292]: https://datatracker.ietf.org/doc/html/rfc7292
|
||||
// [frozen]: https://go.dev/wiki/Frozen
|
||||
package pkcs12
|
||||
|
||||
import (
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package salsa provides low-level access to functions in the Salsa family.
|
||||
//
|
||||
// Deprecated: this package exposes unsafe low-level operations. New applications
|
||||
// should consider using the AEAD construction in golang.org/x/crypto/chacha20poly1305
|
||||
// instead. Existing users should migrate to golang.org/x/crypto/salsa20.
|
||||
package salsa
|
||||
|
||||
import "math/bits"
|
||||
|
||||
@@ -196,6 +196,9 @@ func Key(password, salt []byte, N, r, p, keyLen int) ([]byte, error) {
|
||||
if N <= 1 || N&(N-1) != 0 {
|
||||
return nil, errors.New("scrypt: N must be > 1 and a power of 2")
|
||||
}
|
||||
if r <= 0 || p <= 0 {
|
||||
return nil, errors.New("scrypt: parameters must be > 0")
|
||||
}
|
||||
if uint64(r)*uint64(p) >= 1<<30 || r > maxInt/128/p || r > maxInt/256 || N > maxInt/128/r {
|
||||
return nil, errors.New("scrypt: parameters are too large")
|
||||
}
|
||||
|
||||
@@ -133,6 +133,10 @@ var bad = []testVector{
|
||||
{"p", "s", 1, 1, 1, nil}, // N == 1
|
||||
{"p", "s", 7, 8, 1, nil}, // N is not power of 2
|
||||
{"p", "s", 16, maxInt / 2, maxInt / 2, nil}, // p * r too large
|
||||
{"p", "s", 2, 0, 1, nil}, // r too small
|
||||
{"p", "s", 2, 1, 0, nil}, // p too small
|
||||
{"p", "s", 2, -1, 1, nil}, // r is negative
|
||||
{"p", "s", 2, 1, -1, nil}, // p is negative
|
||||
}
|
||||
|
||||
func TestKey(t *testing.T) {
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
module sha3/_asm
|
||||
|
||||
go 1.22
|
||||
|
||||
require (
|
||||
github.com/mmcloughlin/avo v0.6.0
|
||||
golang.org/x/crypto v0.33.0
|
||||
)
|
||||
|
||||
require (
|
||||
golang.org/x/mod v0.19.0 // indirect
|
||||
golang.org/x/sync v0.7.0 // indirect
|
||||
golang.org/x/sys v0.30.0 // indirect
|
||||
golang.org/x/tools v0.23.0 // indirect
|
||||
)
|
||||
@@ -1,12 +0,0 @@
|
||||
github.com/mmcloughlin/avo v0.6.0 h1:QH6FU8SKoTLaVs80GA8TJuLNkUYl4VokHKlPhVDg4YY=
|
||||
github.com/mmcloughlin/avo v0.6.0/go.mod h1:8CoAGaCSYXtCPR+8y18Y9aB/kxb8JSS6FRI7mSkvD+8=
|
||||
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
|
||||
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
|
||||
golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8=
|
||||
golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
|
||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg=
|
||||
golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI=
|
||||
@@ -1,438 +0,0 @@
|
||||
// Copyright 2024 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// This code was translated into a form compatible with 6a from the public
|
||||
// domain sources at https://github.com/gvanas/KeccakCodePackage
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
. "github.com/mmcloughlin/avo/build"
|
||||
. "github.com/mmcloughlin/avo/operand"
|
||||
. "github.com/mmcloughlin/avo/reg"
|
||||
_ "golang.org/x/crypto/sha3"
|
||||
)
|
||||
|
||||
//go:generate go run . -out ../keccakf_amd64.s -pkg sha3
|
||||
|
||||
// Round Constants for use in the ι step.
|
||||
var RoundConstants = [24]uint64{
|
||||
0x0000000000000001,
|
||||
0x0000000000008082,
|
||||
0x800000000000808A,
|
||||
0x8000000080008000,
|
||||
0x000000000000808B,
|
||||
0x0000000080000001,
|
||||
0x8000000080008081,
|
||||
0x8000000000008009,
|
||||
0x000000000000008A,
|
||||
0x0000000000000088,
|
||||
0x0000000080008009,
|
||||
0x000000008000000A,
|
||||
0x000000008000808B,
|
||||
0x800000000000008B,
|
||||
0x8000000000008089,
|
||||
0x8000000000008003,
|
||||
0x8000000000008002,
|
||||
0x8000000000000080,
|
||||
0x000000000000800A,
|
||||
0x800000008000000A,
|
||||
0x8000000080008081,
|
||||
0x8000000000008080,
|
||||
0x0000000080000001,
|
||||
0x8000000080008008,
|
||||
}
|
||||
|
||||
var (
|
||||
// Temporary registers
|
||||
rT1 GPPhysical = RAX
|
||||
|
||||
// Round vars
|
||||
rpState = Mem{Base: RDI}
|
||||
rpStack = Mem{Base: RSP}
|
||||
|
||||
rDa = RBX
|
||||
rDe = RCX
|
||||
rDi = RDX
|
||||
rDo = R8
|
||||
rDu = R9
|
||||
|
||||
rBa = R10
|
||||
rBe = R11
|
||||
rBi = R12
|
||||
rBo = R13
|
||||
rBu = R14
|
||||
|
||||
rCa = RSI
|
||||
rCe = RBP
|
||||
rCi = rBi
|
||||
rCo = rBo
|
||||
rCu = R15
|
||||
)
|
||||
|
||||
const (
|
||||
_ba = iota * 8
|
||||
_be
|
||||
_bi
|
||||
_bo
|
||||
_bu
|
||||
_ga
|
||||
_ge
|
||||
_gi
|
||||
_go
|
||||
_gu
|
||||
_ka
|
||||
_ke
|
||||
_ki
|
||||
_ko
|
||||
_ku
|
||||
_ma
|
||||
_me
|
||||
_mi
|
||||
_mo
|
||||
_mu
|
||||
_sa
|
||||
_se
|
||||
_si
|
||||
_so
|
||||
_su
|
||||
)
|
||||
|
||||
func main() {
|
||||
Package("golang.org/x/crypto/sha3")
|
||||
ConstraintExpr("amd64,!purego,gc")
|
||||
keccakF1600()
|
||||
Generate()
|
||||
}
|
||||
|
||||
func MOVQ_RBI_RCE() { MOVQ(rBi, rCe) }
|
||||
func XORQ_RT1_RCA() { XORQ(rT1, rCa) }
|
||||
func XORQ_RT1_RCE() { XORQ(rT1, rCe) }
|
||||
func XORQ_RBA_RCU() { XORQ(rBa, rCu) }
|
||||
func XORQ_RBE_RCU() { XORQ(rBe, rCu) }
|
||||
func XORQ_RDU_RCU() { XORQ(rDu, rCu) }
|
||||
func XORQ_RDA_RCA() { XORQ(rDa, rCa) }
|
||||
func XORQ_RDE_RCE() { XORQ(rDe, rCe) }
|
||||
|
||||
type ArgMacro func()
|
||||
|
||||
func mKeccakRound(
|
||||
iState, oState Mem,
|
||||
rc U64,
|
||||
B_RBI_RCE, G_RT1_RCA, G_RT1_RCE, G_RBA_RCU,
|
||||
K_RT1_RCA, K_RT1_RCE, K_RBA_RCU, M_RT1_RCA,
|
||||
M_RT1_RCE, M_RBE_RCU, S_RDU_RCU, S_RDA_RCA,
|
||||
S_RDE_RCE ArgMacro,
|
||||
) {
|
||||
Comment("Prepare round")
|
||||
MOVQ(rCe, rDa)
|
||||
ROLQ(Imm(1), rDa)
|
||||
|
||||
MOVQ(iState.Offset(_bi), rCi)
|
||||
XORQ(iState.Offset(_gi), rDi)
|
||||
XORQ(rCu, rDa)
|
||||
XORQ(iState.Offset(_ki), rCi)
|
||||
XORQ(iState.Offset(_mi), rDi)
|
||||
XORQ(rDi, rCi)
|
||||
|
||||
MOVQ(rCi, rDe)
|
||||
ROLQ(Imm(1), rDe)
|
||||
|
||||
MOVQ(iState.Offset(_bo), rCo)
|
||||
XORQ(iState.Offset(_go), rDo)
|
||||
XORQ(rCa, rDe)
|
||||
XORQ(iState.Offset(_ko), rCo)
|
||||
XORQ(iState.Offset(_mo), rDo)
|
||||
XORQ(rDo, rCo)
|
||||
|
||||
MOVQ(rCo, rDi)
|
||||
ROLQ(Imm(1), rDi)
|
||||
|
||||
MOVQ(rCu, rDo)
|
||||
XORQ(rCe, rDi)
|
||||
ROLQ(Imm(1), rDo)
|
||||
|
||||
MOVQ(rCa, rDu)
|
||||
XORQ(rCi, rDo)
|
||||
ROLQ(Imm(1), rDu)
|
||||
|
||||
Comment("Result b")
|
||||
MOVQ(iState.Offset(_ba), rBa)
|
||||
MOVQ(iState.Offset(_ge), rBe)
|
||||
XORQ(rCo, rDu)
|
||||
MOVQ(iState.Offset(_ki), rBi)
|
||||
MOVQ(iState.Offset(_mo), rBo)
|
||||
MOVQ(iState.Offset(_su), rBu)
|
||||
XORQ(rDe, rBe)
|
||||
ROLQ(Imm(44), rBe)
|
||||
XORQ(rDi, rBi)
|
||||
XORQ(rDa, rBa)
|
||||
ROLQ(Imm(43), rBi)
|
||||
|
||||
MOVQ(rBe, rCa)
|
||||
MOVQ(rc, rT1)
|
||||
ORQ(rBi, rCa)
|
||||
XORQ(rBa, rT1)
|
||||
XORQ(rT1, rCa)
|
||||
MOVQ(rCa, oState.Offset(_ba))
|
||||
|
||||
XORQ(rDu, rBu)
|
||||
ROLQ(Imm(14), rBu)
|
||||
MOVQ(rBa, rCu)
|
||||
ANDQ(rBe, rCu)
|
||||
XORQ(rBu, rCu)
|
||||
MOVQ(rCu, oState.Offset(_bu))
|
||||
|
||||
XORQ(rDo, rBo)
|
||||
ROLQ(Imm(21), rBo)
|
||||
MOVQ(rBo, rT1)
|
||||
ANDQ(rBu, rT1)
|
||||
XORQ(rBi, rT1)
|
||||
MOVQ(rT1, oState.Offset(_bi))
|
||||
|
||||
NOTQ(rBi)
|
||||
ORQ(rBa, rBu)
|
||||
ORQ(rBo, rBi)
|
||||
XORQ(rBo, rBu)
|
||||
XORQ(rBe, rBi)
|
||||
MOVQ(rBu, oState.Offset(_bo))
|
||||
MOVQ(rBi, oState.Offset(_be))
|
||||
B_RBI_RCE()
|
||||
|
||||
Comment("Result g")
|
||||
MOVQ(iState.Offset(_gu), rBe)
|
||||
XORQ(rDu, rBe)
|
||||
MOVQ(iState.Offset(_ka), rBi)
|
||||
ROLQ(Imm(20), rBe)
|
||||
XORQ(rDa, rBi)
|
||||
ROLQ(Imm(3), rBi)
|
||||
MOVQ(iState.Offset(_bo), rBa)
|
||||
MOVQ(rBe, rT1)
|
||||
ORQ(rBi, rT1)
|
||||
XORQ(rDo, rBa)
|
||||
MOVQ(iState.Offset(_me), rBo)
|
||||
MOVQ(iState.Offset(_si), rBu)
|
||||
ROLQ(Imm(28), rBa)
|
||||
XORQ(rBa, rT1)
|
||||
MOVQ(rT1, oState.Offset(_ga))
|
||||
G_RT1_RCA()
|
||||
|
||||
XORQ(rDe, rBo)
|
||||
ROLQ(Imm(45), rBo)
|
||||
MOVQ(rBi, rT1)
|
||||
ANDQ(rBo, rT1)
|
||||
XORQ(rBe, rT1)
|
||||
MOVQ(rT1, oState.Offset(_ge))
|
||||
G_RT1_RCE()
|
||||
|
||||
XORQ(rDi, rBu)
|
||||
ROLQ(Imm(61), rBu)
|
||||
MOVQ(rBu, rT1)
|
||||
ORQ(rBa, rT1)
|
||||
XORQ(rBo, rT1)
|
||||
MOVQ(rT1, oState.Offset(_go))
|
||||
|
||||
ANDQ(rBe, rBa)
|
||||
XORQ(rBu, rBa)
|
||||
MOVQ(rBa, oState.Offset(_gu))
|
||||
NOTQ(rBu)
|
||||
G_RBA_RCU()
|
||||
|
||||
ORQ(rBu, rBo)
|
||||
XORQ(rBi, rBo)
|
||||
MOVQ(rBo, oState.Offset(_gi))
|
||||
|
||||
Comment("Result k")
|
||||
MOVQ(iState.Offset(_be), rBa)
|
||||
MOVQ(iState.Offset(_gi), rBe)
|
||||
MOVQ(iState.Offset(_ko), rBi)
|
||||
MOVQ(iState.Offset(_mu), rBo)
|
||||
MOVQ(iState.Offset(_sa), rBu)
|
||||
XORQ(rDi, rBe)
|
||||
ROLQ(Imm(6), rBe)
|
||||
XORQ(rDo, rBi)
|
||||
ROLQ(Imm(25), rBi)
|
||||
MOVQ(rBe, rT1)
|
||||
ORQ(rBi, rT1)
|
||||
XORQ(rDe, rBa)
|
||||
ROLQ(Imm(1), rBa)
|
||||
XORQ(rBa, rT1)
|
||||
MOVQ(rT1, oState.Offset(_ka))
|
||||
K_RT1_RCA()
|
||||
|
||||
XORQ(rDu, rBo)
|
||||
ROLQ(Imm(8), rBo)
|
||||
MOVQ(rBi, rT1)
|
||||
ANDQ(rBo, rT1)
|
||||
XORQ(rBe, rT1)
|
||||
MOVQ(rT1, oState.Offset(_ke))
|
||||
K_RT1_RCE()
|
||||
|
||||
XORQ(rDa, rBu)
|
||||
ROLQ(Imm(18), rBu)
|
||||
NOTQ(rBo)
|
||||
MOVQ(rBo, rT1)
|
||||
ANDQ(rBu, rT1)
|
||||
XORQ(rBi, rT1)
|
||||
MOVQ(rT1, oState.Offset(_ki))
|
||||
|
||||
MOVQ(rBu, rT1)
|
||||
ORQ(rBa, rT1)
|
||||
XORQ(rBo, rT1)
|
||||
MOVQ(rT1, oState.Offset(_ko))
|
||||
|
||||
ANDQ(rBe, rBa)
|
||||
XORQ(rBu, rBa)
|
||||
MOVQ(rBa, oState.Offset(_ku))
|
||||
K_RBA_RCU()
|
||||
|
||||
Comment("Result m")
|
||||
MOVQ(iState.Offset(_ga), rBe)
|
||||
XORQ(rDa, rBe)
|
||||
MOVQ(iState.Offset(_ke), rBi)
|
||||
ROLQ(Imm(36), rBe)
|
||||
XORQ(rDe, rBi)
|
||||
MOVQ(iState.Offset(_bu), rBa)
|
||||
ROLQ(Imm(10), rBi)
|
||||
MOVQ(rBe, rT1)
|
||||
MOVQ(iState.Offset(_mi), rBo)
|
||||
ANDQ(rBi, rT1)
|
||||
XORQ(rDu, rBa)
|
||||
MOVQ(iState.Offset(_so), rBu)
|
||||
ROLQ(Imm(27), rBa)
|
||||
XORQ(rBa, rT1)
|
||||
MOVQ(rT1, oState.Offset(_ma))
|
||||
M_RT1_RCA()
|
||||
|
||||
XORQ(rDi, rBo)
|
||||
ROLQ(Imm(15), rBo)
|
||||
MOVQ(rBi, rT1)
|
||||
ORQ(rBo, rT1)
|
||||
XORQ(rBe, rT1)
|
||||
MOVQ(rT1, oState.Offset(_me))
|
||||
M_RT1_RCE()
|
||||
|
||||
XORQ(rDo, rBu)
|
||||
ROLQ(Imm(56), rBu)
|
||||
NOTQ(rBo)
|
||||
MOVQ(rBo, rT1)
|
||||
ORQ(rBu, rT1)
|
||||
XORQ(rBi, rT1)
|
||||
MOVQ(rT1, oState.Offset(_mi))
|
||||
|
||||
ORQ(rBa, rBe)
|
||||
XORQ(rBu, rBe)
|
||||
MOVQ(rBe, oState.Offset(_mu))
|
||||
|
||||
ANDQ(rBa, rBu)
|
||||
XORQ(rBo, rBu)
|
||||
MOVQ(rBu, oState.Offset(_mo))
|
||||
M_RBE_RCU()
|
||||
|
||||
Comment("Result s")
|
||||
MOVQ(iState.Offset(_bi), rBa)
|
||||
MOVQ(iState.Offset(_go), rBe)
|
||||
MOVQ(iState.Offset(_ku), rBi)
|
||||
XORQ(rDi, rBa)
|
||||
MOVQ(iState.Offset(_ma), rBo)
|
||||
ROLQ(Imm(62), rBa)
|
||||
XORQ(rDo, rBe)
|
||||
MOVQ(iState.Offset(_se), rBu)
|
||||
ROLQ(Imm(55), rBe)
|
||||
|
||||
XORQ(rDu, rBi)
|
||||
MOVQ(rBa, rDu)
|
||||
XORQ(rDe, rBu)
|
||||
ROLQ(Imm(2), rBu)
|
||||
ANDQ(rBe, rDu)
|
||||
XORQ(rBu, rDu)
|
||||
MOVQ(rDu, oState.Offset(_su))
|
||||
|
||||
ROLQ(Imm(39), rBi)
|
||||
S_RDU_RCU()
|
||||
NOTQ(rBe)
|
||||
XORQ(rDa, rBo)
|
||||
MOVQ(rBe, rDa)
|
||||
ANDQ(rBi, rDa)
|
||||
XORQ(rBa, rDa)
|
||||
MOVQ(rDa, oState.Offset(_sa))
|
||||
S_RDA_RCA()
|
||||
|
||||
ROLQ(Imm(41), rBo)
|
||||
MOVQ(rBi, rDe)
|
||||
ORQ(rBo, rDe)
|
||||
XORQ(rBe, rDe)
|
||||
MOVQ(rDe, oState.Offset(_se))
|
||||
S_RDE_RCE()
|
||||
|
||||
MOVQ(rBo, rDi)
|
||||
MOVQ(rBu, rDo)
|
||||
ANDQ(rBu, rDi)
|
||||
ORQ(rBa, rDo)
|
||||
XORQ(rBi, rDi)
|
||||
XORQ(rBo, rDo)
|
||||
MOVQ(rDi, oState.Offset(_si))
|
||||
MOVQ(rDo, oState.Offset(_so))
|
||||
}
|
||||
|
||||
// keccakF1600 applies the Keccak permutation to a 1600b-wide
|
||||
// state represented as a slice of 25 uint64s.
|
||||
func keccakF1600() {
|
||||
Implement("keccakF1600")
|
||||
AllocLocal(200)
|
||||
|
||||
Load(Param("a"), rpState.Base)
|
||||
|
||||
Comment("Convert the user state into an internal state")
|
||||
NOTQ(rpState.Offset(_be))
|
||||
NOTQ(rpState.Offset(_bi))
|
||||
NOTQ(rpState.Offset(_go))
|
||||
NOTQ(rpState.Offset(_ki))
|
||||
NOTQ(rpState.Offset(_mi))
|
||||
NOTQ(rpState.Offset(_sa))
|
||||
|
||||
Comment("Execute the KeccakF permutation")
|
||||
MOVQ(rpState.Offset(_ba), rCa)
|
||||
MOVQ(rpState.Offset(_be), rCe)
|
||||
MOVQ(rpState.Offset(_bu), rCu)
|
||||
|
||||
XORQ(rpState.Offset(_ga), rCa)
|
||||
XORQ(rpState.Offset(_ge), rCe)
|
||||
XORQ(rpState.Offset(_gu), rCu)
|
||||
|
||||
XORQ(rpState.Offset(_ka), rCa)
|
||||
XORQ(rpState.Offset(_ke), rCe)
|
||||
XORQ(rpState.Offset(_ku), rCu)
|
||||
|
||||
XORQ(rpState.Offset(_ma), rCa)
|
||||
XORQ(rpState.Offset(_me), rCe)
|
||||
XORQ(rpState.Offset(_mu), rCu)
|
||||
|
||||
XORQ(rpState.Offset(_sa), rCa)
|
||||
XORQ(rpState.Offset(_se), rCe)
|
||||
MOVQ(rpState.Offset(_si), rDi)
|
||||
MOVQ(rpState.Offset(_so), rDo)
|
||||
XORQ(rpState.Offset(_su), rCu)
|
||||
|
||||
for i, rc := range RoundConstants[:len(RoundConstants)-1] {
|
||||
var iState, oState Mem
|
||||
if i%2 == 0 {
|
||||
iState, oState = rpState, rpStack
|
||||
} else {
|
||||
iState, oState = rpStack, rpState
|
||||
}
|
||||
mKeccakRound(iState, oState, U64(rc), MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
|
||||
}
|
||||
mKeccakRound(rpStack, rpState, U64(RoundConstants[len(RoundConstants)-1]), NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP)
|
||||
|
||||
Comment("Revert the internal state to the user state")
|
||||
NOTQ(rpState.Offset(_be))
|
||||
NOTQ(rpState.Offset(_bi))
|
||||
NOTQ(rpState.Offset(_go))
|
||||
NOTQ(rpState.Offset(_ki))
|
||||
NOTQ(rpState.Offset(_mi))
|
||||
NOTQ(rpState.Offset(_sa))
|
||||
|
||||
RET()
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
// Copyright 2023 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build !noopt
|
||||
|
||||
package sha3_test
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/crypto/sha3"
|
||||
)
|
||||
|
||||
var sink byte
|
||||
|
||||
func TestAllocations(t *testing.T) {
|
||||
want := 0.0
|
||||
|
||||
if runtime.GOARCH == "s390x" {
|
||||
// On s390x the returned hash.Hash is conditional so it escapes.
|
||||
want = 3.0
|
||||
}
|
||||
|
||||
t.Run("New", func(t *testing.T) {
|
||||
if allocs := testing.AllocsPerRun(10, func() {
|
||||
h := sha3.New256()
|
||||
b := []byte("ABC")
|
||||
h.Write(b)
|
||||
out := make([]byte, 0, 32)
|
||||
out = h.Sum(out)
|
||||
sink ^= out[0]
|
||||
}); allocs > want {
|
||||
t.Errorf("expected zero allocations, got %0.1f", allocs)
|
||||
}
|
||||
})
|
||||
t.Run("NewShake", func(t *testing.T) {
|
||||
if allocs := testing.AllocsPerRun(10, func() {
|
||||
h := sha3.NewShake128()
|
||||
b := []byte("ABC")
|
||||
h.Write(b)
|
||||
out := make([]byte, 0, 32)
|
||||
out = h.Sum(out)
|
||||
sink ^= out[0]
|
||||
h.Read(out)
|
||||
sink ^= out[0]
|
||||
}); allocs > want {
|
||||
t.Errorf("expected zero allocations, got %0.1f", allocs)
|
||||
}
|
||||
})
|
||||
t.Run("Sum", func(t *testing.T) {
|
||||
if allocs := testing.AllocsPerRun(10, func() {
|
||||
b := []byte("ABC")
|
||||
out := sha3.Sum256(b)
|
||||
sink ^= out[0]
|
||||
}); allocs > want {
|
||||
t.Errorf("expected zero allocations, got %0.1f", allocs)
|
||||
}
|
||||
})
|
||||
}
|
||||
-66
@@ -1,66 +0,0 @@
|
||||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package sha3 implements the SHA-3 fixed-output-length hash functions and
|
||||
// the SHAKE variable-output-length hash functions defined by FIPS-202.
|
||||
//
|
||||
// All types in this package also implement [encoding.BinaryMarshaler],
|
||||
// [encoding.BinaryAppender] and [encoding.BinaryUnmarshaler] to marshal and
|
||||
// unmarshal the internal state of the hash.
|
||||
//
|
||||
// Both types of hash function use the "sponge" construction and the Keccak
|
||||
// permutation. For a detailed specification see http://keccak.noekeon.org/
|
||||
//
|
||||
// # Guidance
|
||||
//
|
||||
// If you aren't sure what function you need, use SHAKE256 with at least 64
|
||||
// bytes of output. The SHAKE instances are faster than the SHA3 instances;
|
||||
// the latter have to allocate memory to conform to the hash.Hash interface.
|
||||
//
|
||||
// If you need a secret-key MAC (message authentication code), prepend the
|
||||
// secret key to the input, hash with SHAKE256 and read at least 32 bytes of
|
||||
// output.
|
||||
//
|
||||
// # Security strengths
|
||||
//
|
||||
// The SHA3-x (x equals 224, 256, 384, or 512) functions have a security
|
||||
// strength against preimage attacks of x bits. Since they only produce "x"
|
||||
// bits of output, their collision-resistance is only "x/2" bits.
|
||||
//
|
||||
// The SHAKE-256 and -128 functions have a generic security strength of 256 and
|
||||
// 128 bits against all attacks, provided that at least 2x bits of their output
|
||||
// is used. Requesting more than 64 or 32 bytes of output, respectively, does
|
||||
// not increase the collision-resistance of the SHAKE functions.
|
||||
//
|
||||
// # The sponge construction
|
||||
//
|
||||
// A sponge builds a pseudo-random function from a public pseudo-random
|
||||
// permutation, by applying the permutation to a state of "rate + capacity"
|
||||
// bytes, but hiding "capacity" of the bytes.
|
||||
//
|
||||
// A sponge starts out with a zero state. To hash an input using a sponge, up
|
||||
// to "rate" bytes of the input are XORed into the sponge's state. The sponge
|
||||
// is then "full" and the permutation is applied to "empty" it. This process is
|
||||
// repeated until all the input has been "absorbed". The input is then padded.
|
||||
// The digest is "squeezed" from the sponge in the same way, except that output
|
||||
// is copied out instead of input being XORed in.
|
||||
//
|
||||
// A sponge is parameterized by its generic security strength, which is equal
|
||||
// to half its capacity; capacity + rate is equal to the permutation's width.
|
||||
// Since the KeccakF-1600 permutation is 1600 bits (200 bytes) wide, this means
|
||||
// that the security strength of a sponge instance is equal to (1600 - bitrate) / 2.
|
||||
//
|
||||
// # Recommendations
|
||||
//
|
||||
// The SHAKE functions are recommended for most new uses. They can produce
|
||||
// output of arbitrary length. SHAKE256, with an output length of at least
|
||||
// 64 bytes, provides 256-bit security against all attacks. The Keccak team
|
||||
// recommends it for most applications upgrading from SHA2-512. (NIST chose a
|
||||
// much stronger, but much slower, sponge instance for SHA3-512.)
|
||||
//
|
||||
// The SHA-3 functions are "drop-in" replacements for the SHA-2 functions.
|
||||
// They produce output of the same length, with the same security strengths
|
||||
// against all attacks. This means, in particular, that SHA3-256 only has
|
||||
// 128-bit collision resistance, because its output length is 32 bytes.
|
||||
package sha3
|
||||
+50
-83
@@ -2,127 +2,94 @@
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package sha3 implements the SHA-3 hash algorithms and the SHAKE extendable
|
||||
// output functions defined in FIPS 202.
|
||||
//
|
||||
// Most of this package is a wrapper around the crypto/sha3 package in the
|
||||
// standard library. The only exception is the legacy Keccak hash functions.
|
||||
package sha3
|
||||
|
||||
// This file provides functions for creating instances of the SHA-3
|
||||
// and SHAKE hash functions, as well as utility functions for hashing
|
||||
// bytes.
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/sha3"
|
||||
"hash"
|
||||
)
|
||||
|
||||
// New224 creates a new SHA3-224 hash.
|
||||
// Its generic security strength is 224 bits against preimage attacks,
|
||||
// and 112 bits against collision attacks.
|
||||
//
|
||||
// It is a wrapper for the [sha3.New224] function in the standard library.
|
||||
//
|
||||
//go:fix inline
|
||||
func New224() hash.Hash {
|
||||
return new224()
|
||||
return sha3.New224()
|
||||
}
|
||||
|
||||
// New256 creates a new SHA3-256 hash.
|
||||
// Its generic security strength is 256 bits against preimage attacks,
|
||||
// and 128 bits against collision attacks.
|
||||
//
|
||||
// It is a wrapper for the [sha3.New256] function in the standard library.
|
||||
//
|
||||
//go:fix inline
|
||||
func New256() hash.Hash {
|
||||
return new256()
|
||||
return sha3.New256()
|
||||
}
|
||||
|
||||
// New384 creates a new SHA3-384 hash.
|
||||
// Its generic security strength is 384 bits against preimage attacks,
|
||||
// and 192 bits against collision attacks.
|
||||
//
|
||||
// It is a wrapper for the [sha3.New384] function in the standard library.
|
||||
//
|
||||
//go:fix inline
|
||||
func New384() hash.Hash {
|
||||
return new384()
|
||||
return sha3.New384()
|
||||
}
|
||||
|
||||
// New512 creates a new SHA3-512 hash.
|
||||
// Its generic security strength is 512 bits against preimage attacks,
|
||||
// and 256 bits against collision attacks.
|
||||
//
|
||||
// It is a wrapper for the [sha3.New512] function in the standard library.
|
||||
//
|
||||
//go:fix inline
|
||||
func New512() hash.Hash {
|
||||
return new512()
|
||||
}
|
||||
|
||||
func init() {
|
||||
crypto.RegisterHash(crypto.SHA3_224, New224)
|
||||
crypto.RegisterHash(crypto.SHA3_256, New256)
|
||||
crypto.RegisterHash(crypto.SHA3_384, New384)
|
||||
crypto.RegisterHash(crypto.SHA3_512, New512)
|
||||
}
|
||||
|
||||
const (
|
||||
dsbyteSHA3 = 0b00000110
|
||||
dsbyteKeccak = 0b00000001
|
||||
dsbyteShake = 0b00011111
|
||||
dsbyteCShake = 0b00000100
|
||||
|
||||
// rateK[c] is the rate in bytes for Keccak[c] where c is the capacity in
|
||||
// bits. Given the sponge size is 1600 bits, the rate is 1600 - c bits.
|
||||
rateK256 = (1600 - 256) / 8
|
||||
rateK448 = (1600 - 448) / 8
|
||||
rateK512 = (1600 - 512) / 8
|
||||
rateK768 = (1600 - 768) / 8
|
||||
rateK1024 = (1600 - 1024) / 8
|
||||
)
|
||||
|
||||
func new224Generic() *state {
|
||||
return &state{rate: rateK448, outputLen: 28, dsbyte: dsbyteSHA3}
|
||||
}
|
||||
|
||||
func new256Generic() *state {
|
||||
return &state{rate: rateK512, outputLen: 32, dsbyte: dsbyteSHA3}
|
||||
}
|
||||
|
||||
func new384Generic() *state {
|
||||
return &state{rate: rateK768, outputLen: 48, dsbyte: dsbyteSHA3}
|
||||
}
|
||||
|
||||
func new512Generic() *state {
|
||||
return &state{rate: rateK1024, outputLen: 64, dsbyte: dsbyteSHA3}
|
||||
}
|
||||
|
||||
// NewLegacyKeccak256 creates a new Keccak-256 hash.
|
||||
//
|
||||
// Only use this function if you require compatibility with an existing cryptosystem
|
||||
// that uses non-standard padding. All other users should use New256 instead.
|
||||
func NewLegacyKeccak256() hash.Hash {
|
||||
return &state{rate: rateK512, outputLen: 32, dsbyte: dsbyteKeccak}
|
||||
}
|
||||
|
||||
// NewLegacyKeccak512 creates a new Keccak-512 hash.
|
||||
//
|
||||
// Only use this function if you require compatibility with an existing cryptosystem
|
||||
// that uses non-standard padding. All other users should use New512 instead.
|
||||
func NewLegacyKeccak512() hash.Hash {
|
||||
return &state{rate: rateK1024, outputLen: 64, dsbyte: dsbyteKeccak}
|
||||
return sha3.New512()
|
||||
}
|
||||
|
||||
// Sum224 returns the SHA3-224 digest of the data.
|
||||
func Sum224(data []byte) (digest [28]byte) {
|
||||
h := New224()
|
||||
h.Write(data)
|
||||
h.Sum(digest[:0])
|
||||
return
|
||||
//
|
||||
// It is a wrapper for the [sha3.Sum224] function in the standard library.
|
||||
//
|
||||
//go:fix inline
|
||||
func Sum224(data []byte) [28]byte {
|
||||
return sha3.Sum224(data)
|
||||
}
|
||||
|
||||
// Sum256 returns the SHA3-256 digest of the data.
|
||||
func Sum256(data []byte) (digest [32]byte) {
|
||||
h := New256()
|
||||
h.Write(data)
|
||||
h.Sum(digest[:0])
|
||||
return
|
||||
//
|
||||
// It is a wrapper for the [sha3.Sum256] function in the standard library.
|
||||
//
|
||||
//go:fix inline
|
||||
func Sum256(data []byte) [32]byte {
|
||||
return sha3.Sum256(data)
|
||||
}
|
||||
|
||||
// Sum384 returns the SHA3-384 digest of the data.
|
||||
func Sum384(data []byte) (digest [48]byte) {
|
||||
h := New384()
|
||||
h.Write(data)
|
||||
h.Sum(digest[:0])
|
||||
return
|
||||
//
|
||||
// It is a wrapper for the [sha3.Sum384] function in the standard library.
|
||||
//
|
||||
//go:fix inline
|
||||
func Sum384(data []byte) [48]byte {
|
||||
return sha3.Sum384(data)
|
||||
}
|
||||
|
||||
// Sum512 returns the SHA3-512 digest of the data.
|
||||
func Sum512(data []byte) (digest [64]byte) {
|
||||
h := New512()
|
||||
h.Write(data)
|
||||
h.Sum(digest[:0])
|
||||
return
|
||||
//
|
||||
// It is a wrapper for the [sha3.Sum512] function in the standard library.
|
||||
//
|
||||
//go:fix inline
|
||||
func Sum512(data []byte) [64]byte {
|
||||
return sha3.Sum512(data)
|
||||
}
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
// Copyright 2023 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build !gc || purego || !s390x
|
||||
|
||||
package sha3
|
||||
|
||||
func new224() *state {
|
||||
return new224Generic()
|
||||
}
|
||||
|
||||
func new256() *state {
|
||||
return new256Generic()
|
||||
}
|
||||
|
||||
func new384() *state {
|
||||
return new384Generic()
|
||||
}
|
||||
|
||||
func new512() *state {
|
||||
return new512Generic()
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
// Copyright 2015 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build amd64 && !purego && gc
|
||||
|
||||
package sha3
|
||||
|
||||
// This function is implemented in keccakf_amd64.s.
|
||||
|
||||
//go:noescape
|
||||
|
||||
func keccakF1600(a *[25]uint64)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,15 +4,46 @@
|
||||
|
||||
package sha3
|
||||
|
||||
// This implementation is only used for NewLegacyKeccak256 and
|
||||
// NewLegacyKeccak512, which are not implemented by crypto/sha3.
|
||||
// All other functions in this package are wrappers around crypto/sha3.
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"hash"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/cpu"
|
||||
)
|
||||
|
||||
const (
|
||||
dsbyteKeccak = 0b00000001
|
||||
|
||||
// rateK[c] is the rate in bytes for Keccak[c] where c is the capacity in
|
||||
// bits. Given the sponge size is 1600 bits, the rate is 1600 - c bits.
|
||||
rateK256 = (1600 - 256) / 8
|
||||
rateK512 = (1600 - 512) / 8
|
||||
rateK1024 = (1600 - 1024) / 8
|
||||
)
|
||||
|
||||
// NewLegacyKeccak256 creates a new Keccak-256 hash.
|
||||
//
|
||||
// Only use this function if you require compatibility with an existing cryptosystem
|
||||
// that uses non-standard padding. All other users should use New256 instead.
|
||||
func NewLegacyKeccak256() hash.Hash {
|
||||
return &state{rate: rateK512, outputLen: 32, dsbyte: dsbyteKeccak}
|
||||
}
|
||||
|
||||
// NewLegacyKeccak512 creates a new Keccak-512 hash.
|
||||
//
|
||||
// Only use this function if you require compatibility with an existing cryptosystem
|
||||
// that uses non-standard padding. All other users should use New512 instead.
|
||||
func NewLegacyKeccak512() hash.Hash {
|
||||
return &state{rate: rateK1024, outputLen: 64, dsbyte: dsbyteKeccak}
|
||||
}
|
||||
|
||||
// spongeDirection indicates the direction bytes are flowing through the sponge.
|
||||
type spongeDirection int
|
||||
|
||||
@@ -173,12 +204,9 @@ func (d *state) Sum(in []byte) []byte {
|
||||
}
|
||||
|
||||
const (
|
||||
magicSHA3 = "sha\x08"
|
||||
magicShake = "sha\x09"
|
||||
magicCShake = "sha\x0a"
|
||||
magicKeccak = "sha\x0b"
|
||||
// magic || rate || main state || n || sponge direction
|
||||
marshaledSize = len(magicSHA3) + 1 + 200 + 1 + 1
|
||||
marshaledSize = len(magicKeccak) + 1 + 200 + 1 + 1
|
||||
)
|
||||
|
||||
func (d *state) MarshalBinary() ([]byte, error) {
|
||||
@@ -187,12 +215,6 @@ func (d *state) MarshalBinary() ([]byte, error) {
|
||||
|
||||
func (d *state) AppendBinary(b []byte) ([]byte, error) {
|
||||
switch d.dsbyte {
|
||||
case dsbyteSHA3:
|
||||
b = append(b, magicSHA3...)
|
||||
case dsbyteShake:
|
||||
b = append(b, magicShake...)
|
||||
case dsbyteCShake:
|
||||
b = append(b, magicCShake...)
|
||||
case dsbyteKeccak:
|
||||
b = append(b, magicKeccak...)
|
||||
default:
|
||||
@@ -210,12 +232,9 @@ func (d *state) UnmarshalBinary(b []byte) error {
|
||||
return errors.New("sha3: invalid hash state")
|
||||
}
|
||||
|
||||
magic := string(b[:len(magicSHA3)])
|
||||
b = b[len(magicSHA3):]
|
||||
magic := string(b[:len(magicKeccak)])
|
||||
b = b[len(magicKeccak):]
|
||||
switch {
|
||||
case magic == magicSHA3 && d.dsbyte == dsbyteSHA3:
|
||||
case magic == magicShake && d.dsbyte == dsbyteShake:
|
||||
case magic == magicCShake && d.dsbyte == dsbyteCShake:
|
||||
case magic == magicKeccak && d.dsbyte == dsbyteKeccak:
|
||||
default:
|
||||
return errors.New("sha3: invalid hash state identifier")
|
||||
@@ -2,10 +2,12 @@
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build !amd64 || purego || !gc
|
||||
|
||||
package sha3
|
||||
|
||||
// This implementation is only used for NewLegacyKeccak256 and
|
||||
// NewLegacyKeccak512, which are not implemented by crypto/sha3.
|
||||
// All other functions in this package are wrappers around crypto/sha3.
|
||||
|
||||
import "math/bits"
|
||||
|
||||
// rc stores the round constants for use in the ι step.
|
||||
@@ -1,303 +0,0 @@
|
||||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build gc && !purego
|
||||
|
||||
package sha3
|
||||
|
||||
// This file contains code for using the 'compute intermediate
|
||||
// message digest' (KIMD) and 'compute last message digest' (KLMD)
|
||||
// instructions to compute SHA-3 and SHAKE hashes on IBM Z.
|
||||
|
||||
import (
|
||||
"hash"
|
||||
|
||||
"golang.org/x/sys/cpu"
|
||||
)
|
||||
|
||||
// codes represent 7-bit KIMD/KLMD function codes as defined in
|
||||
// the Principles of Operation.
|
||||
type code uint64
|
||||
|
||||
const (
|
||||
// function codes for KIMD/KLMD
|
||||
sha3_224 code = 32
|
||||
sha3_256 = 33
|
||||
sha3_384 = 34
|
||||
sha3_512 = 35
|
||||
shake_128 = 36
|
||||
shake_256 = 37
|
||||
nopad = 0x100
|
||||
)
|
||||
|
||||
// kimd is a wrapper for the 'compute intermediate message digest' instruction.
|
||||
// src must be a multiple of the rate for the given function code.
|
||||
//
|
||||
//go:noescape
|
||||
func kimd(function code, chain *[200]byte, src []byte)
|
||||
|
||||
// klmd is a wrapper for the 'compute last message digest' instruction.
|
||||
// src padding is handled by the instruction.
|
||||
//
|
||||
//go:noescape
|
||||
func klmd(function code, chain *[200]byte, dst, src []byte)
|
||||
|
||||
type asmState struct {
|
||||
a [200]byte // 1600 bit state
|
||||
buf []byte // care must be taken to ensure cap(buf) is a multiple of rate
|
||||
rate int // equivalent to block size
|
||||
storage [3072]byte // underlying storage for buf
|
||||
outputLen int // output length for full security
|
||||
function code // KIMD/KLMD function code
|
||||
state spongeDirection // whether the sponge is absorbing or squeezing
|
||||
}
|
||||
|
||||
func newAsmState(function code) *asmState {
|
||||
var s asmState
|
||||
s.function = function
|
||||
switch function {
|
||||
case sha3_224:
|
||||
s.rate = 144
|
||||
s.outputLen = 28
|
||||
case sha3_256:
|
||||
s.rate = 136
|
||||
s.outputLen = 32
|
||||
case sha3_384:
|
||||
s.rate = 104
|
||||
s.outputLen = 48
|
||||
case sha3_512:
|
||||
s.rate = 72
|
||||
s.outputLen = 64
|
||||
case shake_128:
|
||||
s.rate = 168
|
||||
s.outputLen = 32
|
||||
case shake_256:
|
||||
s.rate = 136
|
||||
s.outputLen = 64
|
||||
default:
|
||||
panic("sha3: unrecognized function code")
|
||||
}
|
||||
|
||||
// limit s.buf size to a multiple of s.rate
|
||||
s.resetBuf()
|
||||
return &s
|
||||
}
|
||||
|
||||
func (s *asmState) clone() *asmState {
|
||||
c := *s
|
||||
c.buf = c.storage[:len(s.buf):cap(s.buf)]
|
||||
return &c
|
||||
}
|
||||
|
||||
// copyIntoBuf copies b into buf. It will panic if there is not enough space to
|
||||
// store all of b.
|
||||
func (s *asmState) copyIntoBuf(b []byte) {
|
||||
bufLen := len(s.buf)
|
||||
s.buf = s.buf[:len(s.buf)+len(b)]
|
||||
copy(s.buf[bufLen:], b)
|
||||
}
|
||||
|
||||
// resetBuf points buf at storage, sets the length to 0 and sets cap to be a
|
||||
// multiple of the rate.
|
||||
func (s *asmState) resetBuf() {
|
||||
max := (cap(s.storage) / s.rate) * s.rate
|
||||
s.buf = s.storage[:0:max]
|
||||
}
|
||||
|
||||
// Write (via the embedded io.Writer interface) adds more data to the running hash.
|
||||
// It never returns an error.
|
||||
func (s *asmState) Write(b []byte) (int, error) {
|
||||
if s.state != spongeAbsorbing {
|
||||
panic("sha3: Write after Read")
|
||||
}
|
||||
length := len(b)
|
||||
for len(b) > 0 {
|
||||
if len(s.buf) == 0 && len(b) >= cap(s.buf) {
|
||||
// Hash the data directly and push any remaining bytes
|
||||
// into the buffer.
|
||||
remainder := len(b) % s.rate
|
||||
kimd(s.function, &s.a, b[:len(b)-remainder])
|
||||
if remainder != 0 {
|
||||
s.copyIntoBuf(b[len(b)-remainder:])
|
||||
}
|
||||
return length, nil
|
||||
}
|
||||
|
||||
if len(s.buf) == cap(s.buf) {
|
||||
// flush the buffer
|
||||
kimd(s.function, &s.a, s.buf)
|
||||
s.buf = s.buf[:0]
|
||||
}
|
||||
|
||||
// copy as much as we can into the buffer
|
||||
n := len(b)
|
||||
if len(b) > cap(s.buf)-len(s.buf) {
|
||||
n = cap(s.buf) - len(s.buf)
|
||||
}
|
||||
s.copyIntoBuf(b[:n])
|
||||
b = b[n:]
|
||||
}
|
||||
return length, nil
|
||||
}
|
||||
|
||||
// Read squeezes an arbitrary number of bytes from the sponge.
|
||||
func (s *asmState) Read(out []byte) (n int, err error) {
|
||||
// The 'compute last message digest' instruction only stores the digest
|
||||
// at the first operand (dst) for SHAKE functions.
|
||||
if s.function != shake_128 && s.function != shake_256 {
|
||||
panic("sha3: can only call Read for SHAKE functions")
|
||||
}
|
||||
|
||||
n = len(out)
|
||||
|
||||
// need to pad if we were absorbing
|
||||
if s.state == spongeAbsorbing {
|
||||
s.state = spongeSqueezing
|
||||
|
||||
// write hash directly into out if possible
|
||||
if len(out)%s.rate == 0 {
|
||||
klmd(s.function, &s.a, out, s.buf) // len(out) may be 0
|
||||
s.buf = s.buf[:0]
|
||||
return
|
||||
}
|
||||
|
||||
// write hash into buffer
|
||||
max := cap(s.buf)
|
||||
if max > len(out) {
|
||||
max = (len(out)/s.rate)*s.rate + s.rate
|
||||
}
|
||||
klmd(s.function, &s.a, s.buf[:max], s.buf)
|
||||
s.buf = s.buf[:max]
|
||||
}
|
||||
|
||||
for len(out) > 0 {
|
||||
// flush the buffer
|
||||
if len(s.buf) != 0 {
|
||||
c := copy(out, s.buf)
|
||||
out = out[c:]
|
||||
s.buf = s.buf[c:]
|
||||
continue
|
||||
}
|
||||
|
||||
// write hash directly into out if possible
|
||||
if len(out)%s.rate == 0 {
|
||||
klmd(s.function|nopad, &s.a, out, nil)
|
||||
return
|
||||
}
|
||||
|
||||
// write hash into buffer
|
||||
s.resetBuf()
|
||||
if cap(s.buf) > len(out) {
|
||||
s.buf = s.buf[:(len(out)/s.rate)*s.rate+s.rate]
|
||||
}
|
||||
klmd(s.function|nopad, &s.a, s.buf, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Sum appends the current hash to b and returns the resulting slice.
|
||||
// It does not change the underlying hash state.
|
||||
func (s *asmState) Sum(b []byte) []byte {
|
||||
if s.state != spongeAbsorbing {
|
||||
panic("sha3: Sum after Read")
|
||||
}
|
||||
|
||||
// Copy the state to preserve the original.
|
||||
a := s.a
|
||||
|
||||
// Hash the buffer. Note that we don't clear it because we
|
||||
// aren't updating the state.
|
||||
switch s.function {
|
||||
case sha3_224, sha3_256, sha3_384, sha3_512:
|
||||
klmd(s.function, &a, nil, s.buf)
|
||||
return append(b, a[:s.outputLen]...)
|
||||
case shake_128, shake_256:
|
||||
d := make([]byte, s.outputLen, 64)
|
||||
klmd(s.function, &a, d, s.buf)
|
||||
return append(b, d[:s.outputLen]...)
|
||||
default:
|
||||
panic("sha3: unknown function")
|
||||
}
|
||||
}
|
||||
|
||||
// Reset resets the Hash to its initial state.
|
||||
func (s *asmState) Reset() {
|
||||
for i := range s.a {
|
||||
s.a[i] = 0
|
||||
}
|
||||
s.resetBuf()
|
||||
s.state = spongeAbsorbing
|
||||
}
|
||||
|
||||
// Size returns the number of bytes Sum will return.
|
||||
func (s *asmState) Size() int {
|
||||
return s.outputLen
|
||||
}
|
||||
|
||||
// BlockSize returns the hash's underlying block size.
|
||||
// The Write method must be able to accept any amount
|
||||
// of data, but it may operate more efficiently if all writes
|
||||
// are a multiple of the block size.
|
||||
func (s *asmState) BlockSize() int {
|
||||
return s.rate
|
||||
}
|
||||
|
||||
// Clone returns a copy of the ShakeHash in its current state.
|
||||
func (s *asmState) Clone() ShakeHash {
|
||||
return s.clone()
|
||||
}
|
||||
|
||||
// new224 returns an assembly implementation of SHA3-224 if available,
|
||||
// otherwise it returns a generic implementation.
|
||||
func new224() hash.Hash {
|
||||
if cpu.S390X.HasSHA3 {
|
||||
return newAsmState(sha3_224)
|
||||
}
|
||||
return new224Generic()
|
||||
}
|
||||
|
||||
// new256 returns an assembly implementation of SHA3-256 if available,
|
||||
// otherwise it returns a generic implementation.
|
||||
func new256() hash.Hash {
|
||||
if cpu.S390X.HasSHA3 {
|
||||
return newAsmState(sha3_256)
|
||||
}
|
||||
return new256Generic()
|
||||
}
|
||||
|
||||
// new384 returns an assembly implementation of SHA3-384 if available,
|
||||
// otherwise it returns a generic implementation.
|
||||
func new384() hash.Hash {
|
||||
if cpu.S390X.HasSHA3 {
|
||||
return newAsmState(sha3_384)
|
||||
}
|
||||
return new384Generic()
|
||||
}
|
||||
|
||||
// new512 returns an assembly implementation of SHA3-512 if available,
|
||||
// otherwise it returns a generic implementation.
|
||||
func new512() hash.Hash {
|
||||
if cpu.S390X.HasSHA3 {
|
||||
return newAsmState(sha3_512)
|
||||
}
|
||||
return new512Generic()
|
||||
}
|
||||
|
||||
// newShake128 returns an assembly implementation of SHAKE-128 if available,
|
||||
// otherwise it returns a generic implementation.
|
||||
func newShake128() ShakeHash {
|
||||
if cpu.S390X.HasSHA3 {
|
||||
return newAsmState(shake_128)
|
||||
}
|
||||
return newShake128Generic()
|
||||
}
|
||||
|
||||
// newShake256 returns an assembly implementation of SHAKE-256 if available,
|
||||
// otherwise it returns a generic implementation.
|
||||
func newShake256() ShakeHash {
|
||||
if cpu.S390X.HasSHA3 {
|
||||
return newAsmState(shake_256)
|
||||
}
|
||||
return newShake256Generic()
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build gc && !purego
|
||||
|
||||
#include "textflag.h"
|
||||
|
||||
// func kimd(function code, chain *[200]byte, src []byte)
|
||||
TEXT ·kimd(SB), NOFRAME|NOSPLIT, $0-40
|
||||
MOVD function+0(FP), R0
|
||||
MOVD chain+8(FP), R1
|
||||
LMG src+16(FP), R2, R3 // R2=base, R3=len
|
||||
|
||||
continue:
|
||||
WORD $0xB93E0002 // KIMD --, R2
|
||||
BVS continue // continue if interrupted
|
||||
MOVD $0, R0 // reset R0 for pre-go1.8 compilers
|
||||
RET
|
||||
|
||||
// func klmd(function code, chain *[200]byte, dst, src []byte)
|
||||
TEXT ·klmd(SB), NOFRAME|NOSPLIT, $0-64
|
||||
// TODO: SHAKE support
|
||||
MOVD function+0(FP), R0
|
||||
MOVD chain+8(FP), R1
|
||||
LMG dst+16(FP), R2, R3 // R2=base, R3=len
|
||||
LMG src+40(FP), R4, R5 // R4=base, R5=len
|
||||
|
||||
continue:
|
||||
WORD $0xB93F0024 // KLMD R2, R4
|
||||
BVS continue // continue if interrupted
|
||||
MOVD $0, R0 // reset R0 for pre-go1.8 compilers
|
||||
RET
|
||||
@@ -16,7 +16,6 @@ import (
|
||||
"encoding"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"math/rand"
|
||||
@@ -523,124 +522,3 @@ func testMarshalUnmarshal(t *testing.T, h hash.Hash) {
|
||||
t.Errorf("got %x, want %x", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkPermutationFunction measures the speed of the permutation function
|
||||
// with no input data.
|
||||
func BenchmarkPermutationFunction(b *testing.B) {
|
||||
b.SetBytes(int64(200))
|
||||
var lanes [25]uint64
|
||||
for i := 0; i < b.N; i++ {
|
||||
keccakF1600(&lanes)
|
||||
}
|
||||
}
|
||||
|
||||
// benchmarkHash tests the speed to hash num buffers of buflen each.
|
||||
func benchmarkHash(b *testing.B, h hash.Hash, size, num int) {
|
||||
b.StopTimer()
|
||||
h.Reset()
|
||||
data := sequentialBytes(size)
|
||||
b.SetBytes(int64(size * num))
|
||||
b.StartTimer()
|
||||
|
||||
var state []byte
|
||||
for i := 0; i < b.N; i++ {
|
||||
for j := 0; j < num; j++ {
|
||||
h.Write(data)
|
||||
}
|
||||
state = h.Sum(state[:0])
|
||||
}
|
||||
b.StopTimer()
|
||||
h.Reset()
|
||||
}
|
||||
|
||||
// benchmarkShake is specialized to the Shake instances, which don't
|
||||
// require a copy on reading output.
|
||||
func benchmarkShake(b *testing.B, h ShakeHash, size, num int) {
|
||||
b.StopTimer()
|
||||
h.Reset()
|
||||
data := sequentialBytes(size)
|
||||
d := make([]byte, 32)
|
||||
|
||||
b.SetBytes(int64(size * num))
|
||||
b.StartTimer()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
h.Reset()
|
||||
for j := 0; j < num; j++ {
|
||||
h.Write(data)
|
||||
}
|
||||
h.Read(d)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkSha3_512_MTU(b *testing.B) { benchmarkHash(b, New512(), 1350, 1) }
|
||||
func BenchmarkSha3_384_MTU(b *testing.B) { benchmarkHash(b, New384(), 1350, 1) }
|
||||
func BenchmarkSha3_256_MTU(b *testing.B) { benchmarkHash(b, New256(), 1350, 1) }
|
||||
func BenchmarkSha3_224_MTU(b *testing.B) { benchmarkHash(b, New224(), 1350, 1) }
|
||||
|
||||
func BenchmarkShake128_MTU(b *testing.B) { benchmarkShake(b, NewShake128(), 1350, 1) }
|
||||
func BenchmarkShake256_MTU(b *testing.B) { benchmarkShake(b, NewShake256(), 1350, 1) }
|
||||
func BenchmarkShake256_16x(b *testing.B) { benchmarkShake(b, NewShake256(), 16, 1024) }
|
||||
func BenchmarkShake256_1MiB(b *testing.B) { benchmarkShake(b, NewShake256(), 1024, 1024) }
|
||||
|
||||
func BenchmarkSha3_512_1MiB(b *testing.B) { benchmarkHash(b, New512(), 1024, 1024) }
|
||||
|
||||
func Example_sum() {
|
||||
buf := []byte("some data to hash")
|
||||
// A hash needs to be 64 bytes long to have 256-bit collision resistance.
|
||||
h := make([]byte, 64)
|
||||
// Compute a 64-byte hash of buf and put it in h.
|
||||
ShakeSum256(h, buf)
|
||||
fmt.Printf("%x\n", h)
|
||||
// Output: 0f65fe41fc353e52c55667bb9e2b27bfcc8476f2c413e9437d272ee3194a4e3146d05ec04a25d16b8f577c19b82d16b1424c3e022e783d2b4da98de3658d363d
|
||||
}
|
||||
|
||||
func Example_mac() {
|
||||
k := []byte("this is a secret key; you should generate a strong random key that's at least 32 bytes long")
|
||||
buf := []byte("and this is some data to authenticate")
|
||||
// A MAC with 32 bytes of output has 256-bit security strength -- if you use at least a 32-byte-long key.
|
||||
h := make([]byte, 32)
|
||||
d := NewShake256()
|
||||
// Write the key into the hash.
|
||||
d.Write(k)
|
||||
// Now write the data.
|
||||
d.Write(buf)
|
||||
// Read 32 bytes of output from the hash into h.
|
||||
d.Read(h)
|
||||
fmt.Printf("%x\n", h)
|
||||
// Output: 78de2974bd2711d5549ffd32b753ef0f5fa80a0db2556db60f0987eb8a9218ff
|
||||
}
|
||||
|
||||
func ExampleNewCShake256() {
|
||||
out := make([]byte, 32)
|
||||
msg := []byte("The quick brown fox jumps over the lazy dog")
|
||||
|
||||
// Example 1: Simple cshake
|
||||
c1 := NewCShake256([]byte("NAME"), []byte("Partition1"))
|
||||
c1.Write(msg)
|
||||
c1.Read(out)
|
||||
fmt.Println(hex.EncodeToString(out))
|
||||
|
||||
// Example 2: Different customization string produces different digest
|
||||
c1 = NewCShake256([]byte("NAME"), []byte("Partition2"))
|
||||
c1.Write(msg)
|
||||
c1.Read(out)
|
||||
fmt.Println(hex.EncodeToString(out))
|
||||
|
||||
// Example 3: Longer output length produces longer digest
|
||||
out = make([]byte, 64)
|
||||
c1 = NewCShake256([]byte("NAME"), []byte("Partition1"))
|
||||
c1.Write(msg)
|
||||
c1.Read(out)
|
||||
fmt.Println(hex.EncodeToString(out))
|
||||
|
||||
// Example 4: Next read produces different result
|
||||
c1.Read(out)
|
||||
fmt.Println(hex.EncodeToString(out))
|
||||
|
||||
// Output:
|
||||
//a90a4c6ca9af2156eba43dc8398279e6b60dcd56fb21837afe6c308fd4ceb05b
|
||||
//a8db03e71f3e4da5c4eee9d28333cdd355f51cef3c567e59be5beb4ecdbb28f0
|
||||
//a90a4c6ca9af2156eba43dc8398279e6b60dcd56fb21837afe6c308fd4ceb05b9dd98c6ee866ca7dc5a39d53e960f400bcd5a19c8a2d6ec6459f63696543a0d8
|
||||
//85e73a72228d08b46515553ca3a29d47df3047e5d84b12d6c2c63e579f4fd1105716b7838e92e981863907f434bfd4443c9e56ea09da998d2f9b47db71988109
|
||||
}
|
||||
|
||||
+49
-123
@@ -4,24 +4,10 @@
|
||||
|
||||
package sha3
|
||||
|
||||
// This file defines the ShakeHash interface, and provides
|
||||
// functions for creating SHAKE and cSHAKE instances, as well as utility
|
||||
// functions for hashing bytes to arbitrary-length output.
|
||||
//
|
||||
//
|
||||
// SHAKE implementation is based on FIPS PUB 202 [1]
|
||||
// cSHAKE implementations is based on NIST SP 800-185 [2]
|
||||
//
|
||||
// [1] https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf
|
||||
// [2] https://doi.org/10.6028/NIST.SP.800-185
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"crypto/sha3"
|
||||
"hash"
|
||||
"io"
|
||||
"math/bits"
|
||||
)
|
||||
|
||||
// ShakeHash defines the interface to hash functions that support
|
||||
@@ -32,7 +18,7 @@ type ShakeHash interface {
|
||||
hash.Hash
|
||||
|
||||
// Read reads more output from the hash; reading affects the hash's
|
||||
// state. (ShakeHash.Read is thus very different from Hash.Sum)
|
||||
// state. (ShakeHash.Read is thus very different from Hash.Sum.)
|
||||
// It never returns an error, but subsequent calls to Write or Sum
|
||||
// will panic.
|
||||
io.Reader
|
||||
@@ -41,115 +27,18 @@ type ShakeHash interface {
|
||||
Clone() ShakeHash
|
||||
}
|
||||
|
||||
// cSHAKE specific context
|
||||
type cshakeState struct {
|
||||
*state // SHA-3 state context and Read/Write operations
|
||||
|
||||
// initBlock is the cSHAKE specific initialization set of bytes. It is initialized
|
||||
// by newCShake function and stores concatenation of N followed by S, encoded
|
||||
// by the method specified in 3.3 of [1].
|
||||
// It is stored here in order for Reset() to be able to put context into
|
||||
// initial state.
|
||||
initBlock []byte
|
||||
}
|
||||
|
||||
func bytepad(data []byte, rate int) []byte {
|
||||
out := make([]byte, 0, 9+len(data)+rate-1)
|
||||
out = append(out, leftEncode(uint64(rate))...)
|
||||
out = append(out, data...)
|
||||
if padlen := rate - len(out)%rate; padlen < rate {
|
||||
out = append(out, make([]byte, padlen)...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func leftEncode(x uint64) []byte {
|
||||
// Let n be the smallest positive integer for which 2^(8n) > x.
|
||||
n := (bits.Len64(x) + 7) / 8
|
||||
if n == 0 {
|
||||
n = 1
|
||||
}
|
||||
// Return n || x with n as a byte and x an n bytes in big-endian order.
|
||||
b := make([]byte, 9)
|
||||
binary.BigEndian.PutUint64(b[1:], x)
|
||||
b = b[9-n-1:]
|
||||
b[0] = byte(n)
|
||||
return b
|
||||
}
|
||||
|
||||
func newCShake(N, S []byte, rate, outputLen int, dsbyte byte) ShakeHash {
|
||||
c := cshakeState{state: &state{rate: rate, outputLen: outputLen, dsbyte: dsbyte}}
|
||||
c.initBlock = make([]byte, 0, 9+len(N)+9+len(S)) // leftEncode returns max 9 bytes
|
||||
c.initBlock = append(c.initBlock, leftEncode(uint64(len(N))*8)...)
|
||||
c.initBlock = append(c.initBlock, N...)
|
||||
c.initBlock = append(c.initBlock, leftEncode(uint64(len(S))*8)...)
|
||||
c.initBlock = append(c.initBlock, S...)
|
||||
c.Write(bytepad(c.initBlock, c.rate))
|
||||
return &c
|
||||
}
|
||||
|
||||
// Reset resets the hash to initial state.
|
||||
func (c *cshakeState) Reset() {
|
||||
c.state.Reset()
|
||||
c.Write(bytepad(c.initBlock, c.rate))
|
||||
}
|
||||
|
||||
// Clone returns copy of a cSHAKE context within its current state.
|
||||
func (c *cshakeState) Clone() ShakeHash {
|
||||
b := make([]byte, len(c.initBlock))
|
||||
copy(b, c.initBlock)
|
||||
return &cshakeState{state: c.clone(), initBlock: b}
|
||||
}
|
||||
|
||||
// Clone returns copy of SHAKE context within its current state.
|
||||
func (c *state) Clone() ShakeHash {
|
||||
return c.clone()
|
||||
}
|
||||
|
||||
func (c *cshakeState) MarshalBinary() ([]byte, error) {
|
||||
return c.AppendBinary(make([]byte, 0, marshaledSize+len(c.initBlock)))
|
||||
}
|
||||
|
||||
func (c *cshakeState) AppendBinary(b []byte) ([]byte, error) {
|
||||
b, err := c.state.AppendBinary(b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b = append(b, c.initBlock...)
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (c *cshakeState) UnmarshalBinary(b []byte) error {
|
||||
if len(b) <= marshaledSize {
|
||||
return errors.New("sha3: invalid hash state")
|
||||
}
|
||||
if err := c.state.UnmarshalBinary(b[:marshaledSize]); err != nil {
|
||||
return err
|
||||
}
|
||||
c.initBlock = bytes.Clone(b[marshaledSize:])
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewShake128 creates a new SHAKE128 variable-output-length ShakeHash.
|
||||
// Its generic security strength is 128 bits against all attacks if at
|
||||
// least 32 bytes of its output are used.
|
||||
func NewShake128() ShakeHash {
|
||||
return newShake128()
|
||||
return &shakeWrapper{sha3.NewSHAKE128(), 32, false, sha3.NewSHAKE128}
|
||||
}
|
||||
|
||||
// NewShake256 creates a new SHAKE256 variable-output-length ShakeHash.
|
||||
// Its generic security strength is 256 bits against all attacks if
|
||||
// at least 64 bytes of its output are used.
|
||||
func NewShake256() ShakeHash {
|
||||
return newShake256()
|
||||
}
|
||||
|
||||
func newShake128Generic() *state {
|
||||
return &state{rate: rateK256, outputLen: 32, dsbyte: dsbyteShake}
|
||||
}
|
||||
|
||||
func newShake256Generic() *state {
|
||||
return &state{rate: rateK512, outputLen: 64, dsbyte: dsbyteShake}
|
||||
return &shakeWrapper{sha3.NewSHAKE256(), 64, false, sha3.NewSHAKE256}
|
||||
}
|
||||
|
||||
// NewCShake128 creates a new instance of cSHAKE128 variable-output-length ShakeHash,
|
||||
@@ -159,10 +48,9 @@ func newShake256Generic() *state {
|
||||
// computations on same input with different S yield unrelated outputs.
|
||||
// When N and S are both empty, this is equivalent to NewShake128.
|
||||
func NewCShake128(N, S []byte) ShakeHash {
|
||||
if len(N) == 0 && len(S) == 0 {
|
||||
return NewShake128()
|
||||
}
|
||||
return newCShake(N, S, rateK256, 32, dsbyteCShake)
|
||||
return &shakeWrapper{sha3.NewCSHAKE128(N, S), 32, false, func() *sha3.SHAKE {
|
||||
return sha3.NewCSHAKE128(N, S)
|
||||
}}
|
||||
}
|
||||
|
||||
// NewCShake256 creates a new instance of cSHAKE256 variable-output-length ShakeHash,
|
||||
@@ -172,10 +60,9 @@ func NewCShake128(N, S []byte) ShakeHash {
|
||||
// computations on same input with different S yield unrelated outputs.
|
||||
// When N and S are both empty, this is equivalent to NewShake256.
|
||||
func NewCShake256(N, S []byte) ShakeHash {
|
||||
if len(N) == 0 && len(S) == 0 {
|
||||
return NewShake256()
|
||||
}
|
||||
return newCShake(N, S, rateK512, 64, dsbyteCShake)
|
||||
return &shakeWrapper{sha3.NewCSHAKE256(N, S), 64, false, func() *sha3.SHAKE {
|
||||
return sha3.NewCSHAKE256(N, S)
|
||||
}}
|
||||
}
|
||||
|
||||
// ShakeSum128 writes an arbitrary-length digest of data into hash.
|
||||
@@ -191,3 +78,42 @@ func ShakeSum256(hash, data []byte) {
|
||||
h.Write(data)
|
||||
h.Read(hash)
|
||||
}
|
||||
|
||||
// shakeWrapper adds the Size, Sum, and Clone methods to a sha3.SHAKE
|
||||
// to implement the ShakeHash interface.
|
||||
type shakeWrapper struct {
|
||||
*sha3.SHAKE
|
||||
outputLen int
|
||||
squeezing bool
|
||||
newSHAKE func() *sha3.SHAKE
|
||||
}
|
||||
|
||||
func (w *shakeWrapper) Read(p []byte) (n int, err error) {
|
||||
w.squeezing = true
|
||||
return w.SHAKE.Read(p)
|
||||
}
|
||||
|
||||
func (w *shakeWrapper) Clone() ShakeHash {
|
||||
s := w.newSHAKE()
|
||||
b, err := w.MarshalBinary()
|
||||
if err != nil {
|
||||
panic(err) // unreachable
|
||||
}
|
||||
if err := s.UnmarshalBinary(b); err != nil {
|
||||
panic(err) // unreachable
|
||||
}
|
||||
return &shakeWrapper{s, w.outputLen, w.squeezing, w.newSHAKE}
|
||||
}
|
||||
|
||||
func (w *shakeWrapper) Size() int { return w.outputLen }
|
||||
|
||||
func (w *shakeWrapper) Sum(b []byte) []byte {
|
||||
if w.squeezing {
|
||||
panic("sha3: Sum after Read")
|
||||
}
|
||||
out := make([]byte, w.outputLen)
|
||||
// Clone the state so that we don't affect future Write calls.
|
||||
s := w.Clone()
|
||||
s.Read(out)
|
||||
return append(b, out...)
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
// Copyright 2023 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build !gc || purego || !s390x
|
||||
|
||||
package sha3
|
||||
|
||||
func newShake128() *state {
|
||||
return newShake128Generic()
|
||||
}
|
||||
|
||||
func newShake256() *state {
|
||||
return newShake256Generic()
|
||||
}
|
||||
+237
-5
@@ -26,6 +26,7 @@ import (
|
||||
"io"
|
||||
"math/big"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
@@ -307,17 +308,50 @@ func parseKey(in []byte) (out *Key, rest []byte, err error) {
|
||||
}, record.Rest, nil
|
||||
}
|
||||
|
||||
// pipelineMaxInFlight is the maximum number of outstanding requests the
|
||||
// client will pipeline to the agent before applying backpressure.
|
||||
const pipelineMaxInFlight = 32
|
||||
|
||||
// client is a client for an ssh-agent process.
|
||||
//
|
||||
// Exactly one of pipeline / (mu, conn) is set, chosen by NewClient
|
||||
// based on whether the underlying transport implements io.Closer.
|
||||
type client struct {
|
||||
// conn is typically a *net.UnixConn
|
||||
// pipeline, if non-nil, dispatches requests over a pipelined
|
||||
// connection: requests are written as soon as the wire is
|
||||
// available and responses are routed back to per-call reply
|
||||
// channels in FIFO order by a background reader goroutine.
|
||||
pipeline *pipeline
|
||||
|
||||
// mu and conn are used in fully-serialized mode, when the
|
||||
// transport does not implement io.Closer. Each call takes mu,
|
||||
// writes its request, reads the matching response, and releases
|
||||
// mu before returning. There is no background goroutine.
|
||||
mu sync.Mutex
|
||||
conn io.ReadWriter
|
||||
// mu is used to prevent concurrent access to the agent
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// NewClient returns an Agent that talks to an ssh-agent process over
|
||||
// the given connection.
|
||||
//
|
||||
// If rw also implements io.Closer (like *net.UnixConn and ssh.Channel
|
||||
// do), the returned client pipelines concurrent requests over the
|
||||
// connection: callers can issue Sign and other operations from
|
||||
// multiple goroutines and they will be written to the agent as soon
|
||||
// as the wire is available, rather than waiting for the previous
|
||||
// responses. The ssh-agent protocol still requires responses to be
|
||||
// returned in request order, so a slow request delays subsequent
|
||||
// responses on the same connection (head-of-line blocking).
|
||||
//
|
||||
// Pipelining requires io.Closer because, on a Write error, the
|
||||
// background reader goroutine must be unblocked by closing the
|
||||
// underlying connection. When rw does not implement io.Closer
|
||||
// this is not possible, so NewClient falls back to fully
|
||||
// serializing each request: a single in-flight call at a time.
|
||||
func NewClient(rw io.ReadWriter) ExtendedAgent {
|
||||
if rwc, ok := rw.(io.ReadWriteCloser); ok {
|
||||
return &client{pipeline: newPipeline(rwc)}
|
||||
}
|
||||
return &client{conn: rw}
|
||||
}
|
||||
|
||||
@@ -340,6 +374,16 @@ func (c *client) call(req []byte) (reply interface{}, err error) {
|
||||
// bytes of the response are returned; no unmarshalling is
|
||||
// performed on the response.
|
||||
func (c *client) callRaw(req []byte) (reply []byte, err error) {
|
||||
if c.pipeline != nil {
|
||||
return c.pipeline.call(req)
|
||||
}
|
||||
return c.serialCall(req)
|
||||
}
|
||||
|
||||
// serialCall implements the fully-serialized request/response path
|
||||
// used when the transport is not an io.Closer. It writes req under mu
|
||||
// and reads the matching response before returning.
|
||||
func (c *client) serialCall(req []byte) (reply []byte, err error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
@@ -430,8 +474,9 @@ func (c *client) List() ([]*Key, error) {
|
||||
return keys, nil
|
||||
case *failureAgentMsg:
|
||||
return nil, errors.New("agent: failed to list keys")
|
||||
default:
|
||||
return nil, fmt.Errorf("agent: failed to list keys, unexpected message type %T", msg)
|
||||
}
|
||||
panic("unreachable")
|
||||
}
|
||||
|
||||
// Sign has the agent sign the data using a protocol 2 key as defined
|
||||
@@ -462,8 +507,9 @@ func (c *client) SignWithFlags(key ssh.PublicKey, data []byte, flags SignatureFl
|
||||
return &sig, nil
|
||||
case *failureAgentMsg:
|
||||
return nil, errors.New("agent: failed to sign challenge")
|
||||
default:
|
||||
return nil, fmt.Errorf("agent: failed to sign challenge, unexpected message type %T", msg)
|
||||
}
|
||||
panic("unreachable")
|
||||
}
|
||||
|
||||
// unmarshal parses an agent message in packet, returning the parsed
|
||||
@@ -575,6 +621,9 @@ func (c *client) insertKey(s interface{}, comment string, constraints []byte) er
|
||||
Constraints: constraints,
|
||||
})
|
||||
case ed25519.PrivateKey:
|
||||
if len(k) != ed25519.PrivateKeySize {
|
||||
return fmt.Errorf("agent: bad ED25519 key size: %d", len(k))
|
||||
}
|
||||
req = ssh.Marshal(ed25519KeyMsg{
|
||||
Type: ssh.KeyAlgoED25519,
|
||||
Pub: []byte(k)[32:],
|
||||
@@ -586,6 +635,9 @@ func (c *client) insertKey(s interface{}, comment string, constraints []byte) er
|
||||
// general idiom is to pass ed25519.PrivateKey by value, not by pointer.
|
||||
// We still support the pointer variant for backwards compatibility.
|
||||
case *ed25519.PrivateKey:
|
||||
if len(*k) != ed25519.PrivateKeySize {
|
||||
return fmt.Errorf("agent: bad ED25519 key size: %d", len(*k))
|
||||
}
|
||||
req = ssh.Marshal(ed25519KeyMsg{
|
||||
Type: ssh.KeyAlgoED25519,
|
||||
Pub: []byte(*k)[32:],
|
||||
@@ -661,6 +713,13 @@ func (c *client) Add(key AddedKey) error {
|
||||
constraints = append(constraints, agentConstrainConfirm)
|
||||
}
|
||||
|
||||
for _, ext := range key.ConstraintExtensions {
|
||||
constraints = append(constraints, ssh.Marshal(constrainExtensionAgentMsg{
|
||||
ExtensionName: ext.ExtensionName,
|
||||
ExtensionDetails: ext.ExtensionDetails,
|
||||
})...)
|
||||
}
|
||||
|
||||
cert := key.Certificate
|
||||
if cert == nil {
|
||||
return c.insertKey(key.PrivateKey, key.Comment, constraints)
|
||||
@@ -703,6 +762,9 @@ func (c *client) insertCert(s interface{}, cert *ssh.Certificate, comment string
|
||||
Constraints: constraints,
|
||||
})
|
||||
case ed25519.PrivateKey:
|
||||
if len(k) != ed25519.PrivateKeySize {
|
||||
return fmt.Errorf("agent: bad ED25519 key size: %d", len(k))
|
||||
}
|
||||
req = ssh.Marshal(ed25519CertMsg{
|
||||
Type: cert.Type(),
|
||||
CertBytes: cert.Marshal(),
|
||||
@@ -715,6 +777,9 @@ func (c *client) insertCert(s interface{}, cert *ssh.Certificate, comment string
|
||||
// general idiom is to pass ed25519.PrivateKey by value, not by pointer.
|
||||
// We still support the pointer variant for backwards compatibility.
|
||||
case *ed25519.PrivateKey:
|
||||
if len(*k) != ed25519.PrivateKeySize {
|
||||
return fmt.Errorf("agent: bad ED25519 key size: %d", len(*k))
|
||||
}
|
||||
req = ssh.Marshal(ed25519CertMsg{
|
||||
Type: cert.Type(),
|
||||
CertBytes: cert.Marshal(),
|
||||
@@ -852,3 +917,170 @@ func (c *client) Extension(extensionType string, contents []byte) ([]byte, error
|
||||
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
// pipelineResult carries either a raw agent reply or an error back to a
|
||||
// caller waiting on the response channel.
|
||||
type pipelineResult struct {
|
||||
reply []byte
|
||||
err error
|
||||
}
|
||||
|
||||
// pipeline implements request pipelining over a single agent connection.
|
||||
//
|
||||
// Writers serialize on writeMu to both register a reply channel in the
|
||||
// pending FIFO queue and write the request bytes on the wire; the two
|
||||
// must be atomic so the queue order matches the wire order. A single
|
||||
// reader goroutine decodes responses from the connection and dispatches
|
||||
// each one to the channel at the head of the queue.
|
||||
//
|
||||
// pending is a chan-of-chan acting as a FIFO queue with a fixed
|
||||
// capacity of pipelineMaxInFlight. The outer channel provides ordering
|
||||
// (reads happen in send order) and natural backpressure (a full queue
|
||||
// blocks new writers). Each inner channel is buffered with capacity
|
||||
// one and is sent to exactly once: either by the reader goroutine
|
||||
// with the agent reply, or by shutdown with the terminal error during
|
||||
// drain. The cap-one buffer makes the producer's send non-blocking,
|
||||
// so the reader and shutdown never have to wait for the caller to be
|
||||
// scheduled on the receive.
|
||||
//
|
||||
// When the reader goroutine exits (on read error or protocol
|
||||
// violation), it closes exitCh to wake any writer blocked on the
|
||||
// pending queue, then serializes with any in-flight writer to close
|
||||
// the pending channel, and finally drains the remaining entries
|
||||
// delivering the terminal error to each waiting caller. The
|
||||
// pipeline relies on conn implementing io.Closer so a writer that
|
||||
// hits a Write error can close the connection to unblock the reader
|
||||
// goroutine; NewClient is responsible for only constructing a
|
||||
// pipeline when this guarantee holds.
|
||||
type pipeline struct {
|
||||
conn io.ReadWriteCloser
|
||||
|
||||
writeMu sync.Mutex
|
||||
// pending is the FIFO queue of reply channels with capacity
|
||||
// pipelineMaxInFlight. See type-level documentation.
|
||||
pending chan chan pipelineResult
|
||||
exitCh chan struct{}
|
||||
|
||||
// err carries the terminal error to callers blocked on a closed
|
||||
// pipeline. It is stored exactly once by the reader goroutine
|
||||
// before exitCh is closed; every read happens after observing
|
||||
// exitCh closed, so the load synchronises through the close and
|
||||
// is guaranteed to return the stored value (never nil).
|
||||
err atomic.Pointer[error]
|
||||
}
|
||||
|
||||
func newPipeline(conn io.ReadWriteCloser) *pipeline {
|
||||
p := &pipeline{
|
||||
conn: conn,
|
||||
pending: make(chan chan pipelineResult, pipelineMaxInFlight),
|
||||
exitCh: make(chan struct{}),
|
||||
}
|
||||
go p.readLoop()
|
||||
return p
|
||||
}
|
||||
|
||||
// readLoop decodes responses from conn and dispatches them in FIFO order
|
||||
// to reply channels in pending. On any failure it invokes shutdown.
|
||||
func (p *pipeline) readLoop() {
|
||||
var finalErr error
|
||||
for {
|
||||
var sizeBuf [4]byte
|
||||
if _, err := io.ReadFull(p.conn, sizeBuf[:]); err != nil {
|
||||
finalErr = err
|
||||
break
|
||||
}
|
||||
respSize := binary.BigEndian.Uint32(sizeBuf[:])
|
||||
if respSize > maxAgentResponseBytes {
|
||||
finalErr = errors.New("response too large")
|
||||
break
|
||||
}
|
||||
buf := make([]byte, respSize)
|
||||
if _, err := io.ReadFull(p.conn, buf); err != nil {
|
||||
finalErr = err
|
||||
break
|
||||
}
|
||||
// Successful writes always enqueue before sending bytes, so
|
||||
// pending has a waiting channel for this response.
|
||||
ch := <-p.pending
|
||||
// The reply channel is buffered with capacity 1 and is only
|
||||
// ever written to once, so this send cannot block.
|
||||
ch <- pipelineResult{reply: buf}
|
||||
}
|
||||
p.shutdown(clientErr(finalErr))
|
||||
}
|
||||
|
||||
// shutdown is called exactly once, from readLoop, when the reader is
|
||||
// terminating. It unblocks pending writers and fails all in-flight
|
||||
// requests with finalErr.
|
||||
func (p *pipeline) shutdown(finalErr error) {
|
||||
// Publish the terminal error before closing exitCh so any
|
||||
// writer that subsequently observes exitCh closed sees err.
|
||||
p.err.Store(&finalErr)
|
||||
|
||||
// Wake any writer blocked waiting for a slot in the pending queue.
|
||||
close(p.exitCh)
|
||||
|
||||
// Wait for any writer currently inside its critical section to
|
||||
// complete. After this lock, no new writer can reach the send on
|
||||
// pending: they will observe exitCh closed in the select and bail
|
||||
// out before attempting the send.
|
||||
p.writeMu.Lock()
|
||||
close(p.pending)
|
||||
p.writeMu.Unlock()
|
||||
|
||||
// Drain entries that were enqueued but never answered, delivering
|
||||
// the terminal error to their waiting callers. The reply channels
|
||||
// are buffered (cap 1) and written to exactly once, so these sends
|
||||
// cannot block.
|
||||
for ch := range p.pending {
|
||||
ch <- pipelineResult{err: finalErr}
|
||||
}
|
||||
}
|
||||
|
||||
// call sends req to the agent and returns the matching raw response.
|
||||
func (p *pipeline) call(req []byte) ([]byte, error) {
|
||||
replyCh := make(chan pipelineResult, 1)
|
||||
|
||||
p.writeMu.Lock()
|
||||
|
||||
// Priority check: if the reader has already finished shutdown,
|
||||
// pending is closed and sending to it would panic. Bail out now.
|
||||
// Once we pass this check while holding writeMu, shutdown cannot
|
||||
// complete close(pending) until we release writeMu, so the send
|
||||
// below is safe against concurrent closure.
|
||||
select {
|
||||
case <-p.exitCh:
|
||||
p.writeMu.Unlock()
|
||||
return nil, *p.err.Load()
|
||||
default:
|
||||
}
|
||||
|
||||
// Enqueue the reply channel before writing the request, so FIFO
|
||||
// order on the wire matches FIFO order in the pending queue. The
|
||||
// exitCh arm handles the case where the reader errors while we
|
||||
// block on a full queue.
|
||||
select {
|
||||
case p.pending <- replyCh:
|
||||
case <-p.exitCh:
|
||||
p.writeMu.Unlock()
|
||||
return nil, *p.err.Load()
|
||||
}
|
||||
|
||||
msg := make([]byte, 4+len(req))
|
||||
binary.BigEndian.PutUint32(msg, uint32(len(req)))
|
||||
copy(msg[4:], req)
|
||||
_, werr := p.conn.Write(msg)
|
||||
p.writeMu.Unlock()
|
||||
|
||||
if werr != nil {
|
||||
// The connection is in an undefined state. Close it so the
|
||||
// reader unblocks promptly and triggers shutdown for every
|
||||
// other in-flight caller. NewClient guarantees conn is a
|
||||
// real io.Closer when the pipeline is in use.
|
||||
p.conn.Close()
|
||||
return nil, clientErr(werr)
|
||||
}
|
||||
|
||||
res := <-replyCh
|
||||
return res.reply, res.err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,649 @@
|
||||
// Copyright 2026 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package agent
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestPipelineParallelSigns(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
keyring := NewKeyring()
|
||||
if err := keyring.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"]}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go ServeAgent(keyring, c2)
|
||||
|
||||
client := NewClient(c1)
|
||||
pubKey := testPublicKeys["rsa"]
|
||||
|
||||
const N = 64
|
||||
var wg sync.WaitGroup
|
||||
errCh := make(chan error, N)
|
||||
for i := range N {
|
||||
wg.Go(func() {
|
||||
data := []byte{byte(i), byte(i >> 8)}
|
||||
sig, err := client.Sign(pubKey, data)
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
if err := pubKey.Verify(data, sig); err != nil {
|
||||
errCh <- err
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
close(errCh)
|
||||
for err := range errCh {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPipelineBackpressure(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
|
||||
const total = pipelineMaxInFlight + 8
|
||||
|
||||
// Fake agent: the reader drains requests from the wire independently
|
||||
// of response production, so the write path is never self-blocked.
|
||||
// The responder only writes a canned success reply once unblocked
|
||||
// via gate.
|
||||
var reqsRead int64
|
||||
gate := make(chan struct{}, total)
|
||||
pending := make(chan struct{}, total+pipelineMaxInFlight)
|
||||
readerDone := make(chan struct{})
|
||||
responderDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(readerDone)
|
||||
defer close(pending)
|
||||
for {
|
||||
var sizeBuf [4]byte
|
||||
if _, err := io.ReadFull(c2, sizeBuf[:]); err != nil {
|
||||
return
|
||||
}
|
||||
size := binary.BigEndian.Uint32(sizeBuf[:])
|
||||
req := make([]byte, size)
|
||||
if _, err := io.ReadFull(c2, req); err != nil {
|
||||
return
|
||||
}
|
||||
atomic.AddInt64(&reqsRead, 1)
|
||||
pending <- struct{}{}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer close(responderDone)
|
||||
for range pending {
|
||||
<-gate
|
||||
var out [5]byte
|
||||
binary.BigEndian.PutUint32(out[:4], 1)
|
||||
out[4] = agentSuccess
|
||||
if _, err := c2.Write(out[:]); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
defer func() {
|
||||
c1.Close()
|
||||
c2.Close()
|
||||
<-readerDone
|
||||
<-responderDone
|
||||
}()
|
||||
|
||||
client := NewClient(c1)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, total)
|
||||
for range total {
|
||||
wg.Go(func() {
|
||||
// RemoveAll maps to a simpleCall expecting agentSuccess.
|
||||
if err := client.RemoveAll(); err != nil {
|
||||
errs <- err
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Wait for the client to fill the pipeline.
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if atomic.LoadInt64(&reqsRead) >= pipelineMaxInFlight {
|
||||
break
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
if got := atomic.LoadInt64(&reqsRead); got != pipelineMaxInFlight {
|
||||
t.Errorf("requests in flight before any response: got %d, want %d", got, pipelineMaxInFlight)
|
||||
}
|
||||
|
||||
// Release all responses; every caller should eventually complete.
|
||||
for range total {
|
||||
gate <- struct{}{}
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if got := atomic.LoadInt64(&reqsRead); got != total {
|
||||
t.Errorf("total requests received: got %d, want %d", got, total)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPipelineConnCloseFailsInFlight(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
|
||||
// Server that reads requests but never replies, so all calls are
|
||||
// parked waiting for responses.
|
||||
serverExit := make(chan struct{})
|
||||
go func() {
|
||||
defer close(serverExit)
|
||||
buf := make([]byte, 4096)
|
||||
for {
|
||||
if _, err := c2.Read(buf); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
client := NewClient(c1)
|
||||
|
||||
const N = 8
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, N)
|
||||
for range N {
|
||||
wg.Go(func() {
|
||||
errs <- client.RemoveAll()
|
||||
})
|
||||
}
|
||||
|
||||
// Give callers time to enter the pipeline, then tear down the conn.
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
c1.Close()
|
||||
c2.Close()
|
||||
|
||||
// All callers must return promptly with an error.
|
||||
doneCh := make(chan struct{})
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(doneCh)
|
||||
}()
|
||||
select {
|
||||
case <-doneCh:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("pipelined callers did not complete after conn close")
|
||||
}
|
||||
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
if err == nil {
|
||||
t.Error("expected error after conn close, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
// Subsequent calls also fail fast rather than hanging.
|
||||
errCh := make(chan error, 1)
|
||||
go func() { errCh <- client.RemoveAll() }()
|
||||
select {
|
||||
case err := <-errCh:
|
||||
if err == nil {
|
||||
t.Error("expected error on post-close call, got nil")
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("post-close call hung")
|
||||
}
|
||||
|
||||
<-serverExit
|
||||
}
|
||||
|
||||
// readWriter exposes only io.Reader and io.Writer, hiding any Close
|
||||
// method on the wrapped value so NewClient cannot take the pipelined
|
||||
// path.
|
||||
type readWriter struct {
|
||||
io.Reader
|
||||
io.Writer
|
||||
}
|
||||
|
||||
func TestNewClientSerialFallback(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
keyring := NewKeyring()
|
||||
if err := keyring.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"]}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go ServeAgent(keyring, c2)
|
||||
|
||||
rw := readWriter{Reader: c1, Writer: c1}
|
||||
ag := NewClient(rw)
|
||||
|
||||
ci, ok := ag.(*client)
|
||||
if !ok {
|
||||
t.Fatalf("NewClient: got %T, want *client", ag)
|
||||
}
|
||||
if ci.pipeline != nil {
|
||||
t.Error("NewClient with non-Closer rw: pipeline must be nil")
|
||||
}
|
||||
if ci.conn == nil {
|
||||
t.Error("NewClient with non-Closer rw: conn must be set")
|
||||
}
|
||||
|
||||
// The serialized path correctly handles a request/response cycle.
|
||||
keys, err := ag.List()
|
||||
if err != nil {
|
||||
t.Fatalf("List: %v", err)
|
||||
}
|
||||
if len(keys) != 1 {
|
||||
t.Errorf("List: got %d keys, want 1", len(keys))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSerialFallbackParallelSigns(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
keyring := NewKeyring()
|
||||
if err := keyring.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"]}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go ServeAgent(keyring, c2)
|
||||
|
||||
rw := readWriter{Reader: c1, Writer: c1}
|
||||
ag := NewClient(rw)
|
||||
|
||||
if ci, ok := ag.(*client); !ok {
|
||||
t.Fatalf("NewClient: got %T, want *client", ag)
|
||||
} else if ci.pipeline != nil {
|
||||
t.Fatal("pipeline must be nil for non-Closer rw")
|
||||
}
|
||||
|
||||
pubKey := testPublicKeys["rsa"]
|
||||
|
||||
const N = 64
|
||||
var wg sync.WaitGroup
|
||||
errCh := make(chan error, N)
|
||||
for i := range N {
|
||||
wg.Go(func() {
|
||||
data := []byte{byte(i), byte(i >> 8)}
|
||||
sig, err := ag.Sign(pubKey, data)
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
if err := pubKey.Verify(data, sig); err != nil {
|
||||
errCh <- err
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
close(errCh)
|
||||
for err := range errCh {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
// writeFailConn wraps a net.Conn and forces Write to return an error when
|
||||
// the fail flag is set. Close delegates to the underlying conn so the test
|
||||
// can observe whether the pipeline closed it.
|
||||
type writeFailConn struct {
|
||||
net.Conn
|
||||
fail atomic.Bool
|
||||
}
|
||||
|
||||
func (c *writeFailConn) Write(p []byte) (int, error) {
|
||||
if c.fail.Load() {
|
||||
return 0, errors.New("synthetic write failure")
|
||||
}
|
||||
return c.Conn.Write(p)
|
||||
}
|
||||
|
||||
func TestPipelineWriteErrorClosesConn(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c2.Close()
|
||||
|
||||
// Peer that reads and discards, exiting when the conn closes.
|
||||
serverExit := make(chan struct{})
|
||||
go func() {
|
||||
defer close(serverExit)
|
||||
io.Copy(io.Discard, c2)
|
||||
}()
|
||||
|
||||
wrapper := &writeFailConn{Conn: c1}
|
||||
wrapper.fail.Store(true)
|
||||
|
||||
client := NewClient(wrapper)
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() { errCh <- client.RemoveAll() }()
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
if err == nil {
|
||||
t.Fatal("expected error on forced write failure, got nil")
|
||||
}
|
||||
// The caller whose Write failed must receive the actual
|
||||
// write error, not the reader's "closed connection" error
|
||||
// from the post-shutdown drain.
|
||||
if !strings.Contains(err.Error(), "synthetic write failure") {
|
||||
t.Errorf("got %q, want error containing %q", err, "synthetic write failure")
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("RemoveAll hung after write failure")
|
||||
}
|
||||
|
||||
// The pipeline must have closed the underlying conn, so the peer
|
||||
// goroutine returns from its Read.
|
||||
select {
|
||||
case <-serverExit:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("connection was not closed after write failure")
|
||||
}
|
||||
|
||||
// After shutdown, subsequent calls must also fail promptly.
|
||||
errCh2 := make(chan error, 1)
|
||||
go func() { errCh2 <- client.RemoveAll() }()
|
||||
select {
|
||||
case err := <-errCh2:
|
||||
if err == nil {
|
||||
t.Error("expected error on post-shutdown call, got nil")
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("post-shutdown call hung")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPipelineResponseTooLarge(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
// Server: read the request, then reply with a size header that
|
||||
// exceeds maxAgentResponseBytes. The size check fires before the
|
||||
// body is read, so no body needs to follow.
|
||||
serverDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(serverDone)
|
||||
var sizeBuf [4]byte
|
||||
if _, err := io.ReadFull(c2, sizeBuf[:]); err != nil {
|
||||
return
|
||||
}
|
||||
size := binary.BigEndian.Uint32(sizeBuf[:])
|
||||
if _, err := io.CopyN(io.Discard, c2, int64(size)); err != nil {
|
||||
return
|
||||
}
|
||||
var out [4]byte
|
||||
binary.BigEndian.PutUint32(out[:], maxAgentResponseBytes+1)
|
||||
c2.Write(out[:])
|
||||
}()
|
||||
|
||||
client := NewClient(c1)
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() { errCh <- client.RemoveAll() }()
|
||||
select {
|
||||
case err := <-errCh:
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "response too large") {
|
||||
t.Errorf("got %q, want error containing %q", err, "response too large")
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("call hung")
|
||||
}
|
||||
|
||||
// Subsequent calls must also fail: the pipeline is shut down.
|
||||
errCh2 := make(chan error, 1)
|
||||
go func() { errCh2 <- client.RemoveAll() }()
|
||||
select {
|
||||
case err := <-errCh2:
|
||||
if err == nil {
|
||||
t.Error("expected error on post-shutdown call, got nil")
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("post-shutdown call hung")
|
||||
}
|
||||
|
||||
<-serverDone
|
||||
}
|
||||
|
||||
func TestPipelineShutdownWithBlockedWriter(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
|
||||
// Server drains requests off the wire so writes never block on
|
||||
// backpressure from the transport, but never replies. The reader
|
||||
// goroutine therefore stays parked on Read, never dequeues from
|
||||
// pending, and the queue fills up.
|
||||
var reqsRead int64
|
||||
serverExit := make(chan struct{})
|
||||
go func() {
|
||||
defer close(serverExit)
|
||||
for {
|
||||
var sizeBuf [4]byte
|
||||
if _, err := io.ReadFull(c2, sizeBuf[:]); err != nil {
|
||||
return
|
||||
}
|
||||
size := binary.BigEndian.Uint32(sizeBuf[:])
|
||||
if _, err := io.CopyN(io.Discard, c2, int64(size)); err != nil {
|
||||
return
|
||||
}
|
||||
atomic.AddInt64(&reqsRead, 1)
|
||||
}
|
||||
}()
|
||||
|
||||
client := NewClient(c1)
|
||||
|
||||
const total = pipelineMaxInFlight + 4
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, total)
|
||||
for range total {
|
||||
wg.Go(func() {
|
||||
errs <- client.RemoveAll()
|
||||
})
|
||||
}
|
||||
|
||||
// Wait for the queue to fill: once pipelineMaxInFlight requests
|
||||
// are on the wire, pending is at capacity and the +1 writer is
|
||||
// blocked in the second-select arm; the rest are queued behind
|
||||
// writeMu.
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if atomic.LoadInt64(&reqsRead) >= pipelineMaxInFlight {
|
||||
break
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
if got := atomic.LoadInt64(&reqsRead); got < pipelineMaxInFlight {
|
||||
t.Fatalf("requests on wire: got %d, want >= %d", got, pipelineMaxInFlight)
|
||||
}
|
||||
// Give the +1 writer a moment to actually park in the second
|
||||
// select before we trigger shutdown.
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
// Trigger shutdown: closing the server side makes the client's
|
||||
// reader hit EOF, which calls shutdown(...).
|
||||
c2.Close()
|
||||
|
||||
doneCh := make(chan struct{})
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(doneCh)
|
||||
}()
|
||||
select {
|
||||
case <-doneCh:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("blocked callers did not complete after shutdown")
|
||||
}
|
||||
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
if err == nil {
|
||||
t.Error("expected error after shutdown, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
<-serverExit
|
||||
}
|
||||
|
||||
// multiDeviceAgent simulates an ssh-agent backed by numDevices signing
|
||||
// devices, each of which takes latency to process a request. Incoming
|
||||
// requests are round-robin dispatched to devices, and responses are
|
||||
// serialized back to the wire in request order as the protocol requires.
|
||||
//
|
||||
// The simulation does not emit a semantically meaningful reply; it just
|
||||
// writes a 1-byte SSH_AGENT_SUCCESS after the simulated latency has
|
||||
// elapsed. This is enough to exercise callRaw/simpleCall (RemoveAll).
|
||||
func multiDeviceAgent(t testing.TB, conn io.ReadWriteCloser, numDevices int, latency time.Duration) (done <-chan struct{}) {
|
||||
t.Helper()
|
||||
|
||||
type job struct {
|
||||
ready chan struct{}
|
||||
}
|
||||
|
||||
devices := make([]chan job, numDevices)
|
||||
var devicesWG sync.WaitGroup
|
||||
for i := range numDevices {
|
||||
devices[i] = make(chan job, 1024)
|
||||
ch := devices[i]
|
||||
devicesWG.Go(func() {
|
||||
for j := range ch {
|
||||
time.Sleep(latency)
|
||||
close(j.ready)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Order-preserving responder: responses are written in the same
|
||||
// order the requests were read, regardless of which device finished
|
||||
// first.
|
||||
orderCh := make(chan chan struct{}, 1024)
|
||||
responderDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(responderDone)
|
||||
for ready := range orderCh {
|
||||
<-ready
|
||||
var out [5]byte
|
||||
binary.BigEndian.PutUint32(out[:4], 1)
|
||||
out[4] = agentSuccess
|
||||
if _, err := conn.Write(out[:]); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
finished := make(chan struct{})
|
||||
go func() {
|
||||
defer close(finished)
|
||||
defer func() {
|
||||
close(orderCh)
|
||||
<-responderDone
|
||||
for _, d := range devices {
|
||||
close(d)
|
||||
}
|
||||
devicesWG.Wait()
|
||||
}()
|
||||
next := 0
|
||||
for {
|
||||
var sizeBuf [4]byte
|
||||
if _, err := io.ReadFull(conn, sizeBuf[:]); err != nil {
|
||||
return
|
||||
}
|
||||
size := binary.BigEndian.Uint32(sizeBuf[:])
|
||||
if _, err := io.CopyN(io.Discard, conn, int64(size)); err != nil {
|
||||
return
|
||||
}
|
||||
ready := make(chan struct{})
|
||||
devices[next%numDevices] <- job{ready: ready}
|
||||
next++
|
||||
orderCh <- ready
|
||||
}
|
||||
}()
|
||||
|
||||
return finished
|
||||
}
|
||||
|
||||
// BenchmarkPipelineMultiDevice measures throughput of the pipelined
|
||||
// agent client against a simulated multi-device agent, varying the
|
||||
// number of backend devices.
|
||||
//
|
||||
// Setup: each simulated signing device takes 2ms per request. The
|
||||
// protocol serializes responses in request order, but pipelining lets
|
||||
// the client keep multiple devices busy concurrently; throughput
|
||||
// should scale roughly linearly with numDevices up to the pipeline
|
||||
// depth (pipelineMaxInFlight).
|
||||
//
|
||||
// Run with: go test -benchmem -bench BenchmarkPipelineMultiDevice -benchtime=2s ./ssh/agent/
|
||||
func BenchmarkPipelineMultiDevice(b *testing.B) {
|
||||
const (
|
||||
deviceLatency = 2 * time.Millisecond
|
||||
parallelism = 32
|
||||
)
|
||||
|
||||
for _, numDevices := range []int{1, 2, 4, 8, 16} {
|
||||
b.Run(fmt.Sprintf("Devices=%d", numDevices), func(b *testing.B) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
b.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
serverDone := multiDeviceAgent(b, c2, numDevices, deviceLatency)
|
||||
|
||||
client := NewClient(c1)
|
||||
|
||||
b.ResetTimer()
|
||||
b.SetParallelism(parallelism)
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
if err := client.RemoveAll(); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
b.StopTimer()
|
||||
|
||||
c1.Close()
|
||||
c2.Close()
|
||||
<-serverDone
|
||||
})
|
||||
}
|
||||
}
|
||||
+147
-1
@@ -6,7 +6,9 @@ package agent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
@@ -39,7 +41,11 @@ func startOpenSSHAgent(t *testing.T) (client ExtendedAgent, socket string, clean
|
||||
}
|
||||
|
||||
cmd := exec.Command(bin, "-s")
|
||||
cmd.Env = []string{} // Do not let the user's environment influence ssh-agent behavior.
|
||||
cmd.Env = []string{
|
||||
// ssh-agent creates ~/.ssh and ~/.ssh/agent;
|
||||
// ensure a writeable home directory.
|
||||
"HOME=" + t.TempDir(),
|
||||
} // Do not let the user's environment influence ssh-agent behavior.
|
||||
cmd.Stderr = new(bytes.Buffer)
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
@@ -347,6 +353,53 @@ func TestServerResponseTooLarge(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidResponses(t *testing.T) {
|
||||
a, b, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
done := make(chan struct{})
|
||||
defer func() { <-done }()
|
||||
|
||||
defer a.Close()
|
||||
defer b.Close()
|
||||
|
||||
agent := NewClient(a)
|
||||
go func() {
|
||||
defer close(done)
|
||||
|
||||
resp := []byte{agentSuccess}
|
||||
msg := make([]byte, 4+len(resp))
|
||||
binary.BigEndian.PutUint32(msg[:4], uint32(len(resp)))
|
||||
copy(msg[4:], resp)
|
||||
|
||||
if _, err := b.Write(msg); err != nil {
|
||||
t.Errorf("unexpected error sending agent reply: %v", err)
|
||||
b.Close()
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := b.Write(msg); err != nil {
|
||||
t.Errorf("unexpected error sending agent reply: %v", err)
|
||||
b.Close()
|
||||
}
|
||||
}()
|
||||
_, err = agent.List()
|
||||
if err == nil {
|
||||
t.Fatal("error expected")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "failed to list keys, unexpected message type") {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
_, err = agent.Sign(testPublicKeys["rsa"], []byte("message"))
|
||||
if err == nil {
|
||||
t.Fatal("error expected")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "failed to sign challenge, unexpected message type") {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuth(t *testing.T) {
|
||||
agent, _, cleanup := startOpenSSHAgent(t)
|
||||
defer cleanup()
|
||||
@@ -542,3 +595,96 @@ func TestAgentExtensions(t *testing.T) {
|
||||
t.Fatal("should have gotten agent extension failure")
|
||||
}
|
||||
}
|
||||
|
||||
// capturingAgent records the AddedKey observed on the server side of the
|
||||
// agent protocol. It forwards to a keyring with constraint fields stripped,
|
||||
// so the keyring's own rejection of unsupported constraints does not
|
||||
// interfere with what this test is measuring: the client-side wire
|
||||
// serialization of ConstraintExtensions.
|
||||
type capturingAgent struct {
|
||||
Agent
|
||||
lastAdd AddedKey
|
||||
}
|
||||
|
||||
func newCapturingAgent() *capturingAgent {
|
||||
return &capturingAgent{Agent: NewKeyring()}
|
||||
}
|
||||
|
||||
func (a *capturingAgent) Add(key AddedKey) error {
|
||||
a.lastAdd = key
|
||||
stripped := key
|
||||
stripped.ConstraintExtensions = nil
|
||||
stripped.ConfirmBeforeUse = false
|
||||
return a.Agent.Add(stripped)
|
||||
}
|
||||
|
||||
// TestAddConstraintExtensionsWireFormat verifies that client.Add serializes
|
||||
// ConstraintExtensions into the SSH_AGENTC_ADD_IDENTITY payload and the
|
||||
// server deserializes them back into the AddedKey delivered to the backend.
|
||||
// Regressions in the client marshal loop (missing, swapped fields, wrong
|
||||
// framing) would be invisible to a keyring-based rejection test, which
|
||||
// signals only "extensions were present", not "the right ones arrived".
|
||||
func TestAddConstraintExtensionsWireFormat(t *testing.T) {
|
||||
capturing := newCapturingAgent()
|
||||
client, cleanup := startAgent(t, capturing)
|
||||
defer cleanup()
|
||||
|
||||
constraints := []ConstraintExtension{
|
||||
{ExtensionName: "ext-one@example.com", ExtensionDetails: []byte("details-one")},
|
||||
{ExtensionName: "ext-two@example.com", ExtensionDetails: []byte("\x00\x01\x02\xff")},
|
||||
}
|
||||
|
||||
if err := client.Add(AddedKey{
|
||||
PrivateKey: testPrivateKeys["rsa"],
|
||||
Comment: "wire-format-test",
|
||||
ConstraintExtensions: constraints,
|
||||
}); err != nil {
|
||||
t.Fatalf("client.Add: %v", err)
|
||||
}
|
||||
|
||||
got := capturing.lastAdd.ConstraintExtensions
|
||||
if len(got) != len(constraints) {
|
||||
t.Fatalf("server received %d extensions, want %d", len(got), len(constraints))
|
||||
}
|
||||
for i, want := range constraints {
|
||||
if got[i].ExtensionName != want.ExtensionName {
|
||||
t.Errorf("extension[%d] name: got %q, want %q", i, got[i].ExtensionName, want.ExtensionName)
|
||||
}
|
||||
if !bytes.Equal(got[i].ExtensionDetails, want.ExtensionDetails) {
|
||||
t.Errorf("extension[%d] details: got %x, want %x", i, got[i].ExtensionDetails, want.ExtensionDetails)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddRejectsShortEd25519Key(t *testing.T) {
|
||||
short := ed25519.PrivateKey(make([]byte, 16))
|
||||
// insertCert reaches its ed25519 branch only when AddedKey.Certificate
|
||||
// is non-nil. The length check returns before cert.Type/Marshal run, so
|
||||
// an empty certificate is sufficient to drive the path.
|
||||
emptyCert := &ssh.Certificate{}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
add AddedKey
|
||||
}{
|
||||
{"insertKey value", AddedKey{PrivateKey: short}},
|
||||
{"insertKey pointer", AddedKey{PrivateKey: &short}},
|
||||
{"insertCert value", AddedKey{PrivateKey: short, Certificate: emptyCert}},
|
||||
{"insertCert pointer", AddedKey{PrivateKey: &short, Certificate: emptyCert}},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
client, cleanup := startKeyringAgent(t)
|
||||
defer cleanup()
|
||||
|
||||
err := client.Add(tc.add)
|
||||
if err == nil {
|
||||
t.Fatal("Add accepted ed25519 key shorter than 64 bytes")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "bad ED25519 key size") {
|
||||
t.Errorf("got error %q, want substring %q", err.Error(), "bad ED25519 key size")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+19
-6
@@ -32,8 +32,10 @@ type keyring struct {
|
||||
|
||||
var errLocked = errors.New("agent: locked")
|
||||
|
||||
// NewKeyring returns an Agent that holds keys in memory. It is safe
|
||||
// for concurrent use by multiple goroutines.
|
||||
// NewKeyring returns an Agent that holds keys in memory. It is safe for
|
||||
// concurrent use by multiple goroutines.
|
||||
//
|
||||
// The returned Agent only supports the "lifetime" constraint.
|
||||
func NewKeyring() Agent {
|
||||
return &keyring{}
|
||||
}
|
||||
@@ -112,7 +114,7 @@ func (r *keyring) Unlock(passphrase []byte) error {
|
||||
}
|
||||
|
||||
// expireKeysLocked removes expired keys from the keyring. If a key was added
|
||||
// with a lifetimesecs contraint and seconds >= lifetimesecs seconds have
|
||||
// with a lifetimesecs constraint and seconds >= lifetimesecs seconds have
|
||||
// elapsed, it is removed. The caller *must* be holding the keyring mutex.
|
||||
func (r *keyring) expireKeysLocked() {
|
||||
for _, k := range r.keys {
|
||||
@@ -143,15 +145,26 @@ func (r *keyring) List() ([]*Key, error) {
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// Insert adds a private key to the keyring. If a certificate
|
||||
// is given, that certificate is added as public key. Note that
|
||||
// any constraints given are ignored.
|
||||
// Add adds a private key to the keyring. If a certificate is given, that
|
||||
// certificate is added as public key.
|
||||
//
|
||||
// Add returns an error if key contains ConstraintExtensions or
|
||||
// ConfirmBeforeUse.
|
||||
func (r *keyring) Add(key AddedKey) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.locked {
|
||||
return errLocked
|
||||
}
|
||||
|
||||
if key.ConfirmBeforeUse {
|
||||
return errors.New("agent: confirm before use constraint is not supported")
|
||||
}
|
||||
|
||||
if len(key.ConstraintExtensions) > 0 {
|
||||
return errors.New("agent: constraint extensions are present but not supported")
|
||||
}
|
||||
|
||||
signer, err := ssh.NewSignerFromKey(key.PrivateKey)
|
||||
|
||||
if err != nil {
|
||||
|
||||
@@ -30,7 +30,7 @@ func validateListedKeys(t *testing.T, a Agent, expectedKeys []string) {
|
||||
return
|
||||
}
|
||||
if len(listedKeys) != len(expectedKeys) {
|
||||
t.Fatalf("expeted %d key, got %d", len(expectedKeys), len(listedKeys))
|
||||
t.Fatalf("expected %d key, got %d", len(expectedKeys), len(listedKeys))
|
||||
return
|
||||
}
|
||||
actualKeys := make(map[string]bool)
|
||||
@@ -120,3 +120,42 @@ func TestAddDuplicateKey(t *testing.T) {
|
||||
t.Fatal("key with the updated comment not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddKeyWithConstraints(t *testing.T) {
|
||||
// Verifies the keyring refuses keys carrying constraint extensions it
|
||||
// cannot enforce.
|
||||
agent, cleanup := startKeyringAgent(t)
|
||||
defer cleanup()
|
||||
|
||||
constraints := []ConstraintExtension{
|
||||
{
|
||||
ExtensionName: "extension1",
|
||||
ExtensionDetails: []byte("details1"),
|
||||
},
|
||||
}
|
||||
|
||||
key := testPrivateKeys["rsa"]
|
||||
|
||||
err := agent.Add(AddedKey{
|
||||
PrivateKey: key,
|
||||
ConstraintExtensions: constraints,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("adding a key with unsupported constraints succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddKeyWithConfirmBeforeUse(t *testing.T) {
|
||||
agent, cleanup := startKeyringAgent(t)
|
||||
defer cleanup()
|
||||
|
||||
key := testPrivateKeys["rsa"]
|
||||
|
||||
err := agent.Add(AddedKey{
|
||||
PrivateKey: key,
|
||||
ConfirmBeforeUse: true,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("adding a key with confirm before use constraint succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
+36
-5
@@ -36,7 +36,7 @@ func (s *server) processRequestBytes(reqData []byte) []byte {
|
||||
return []byte{agentFailure}
|
||||
}
|
||||
|
||||
if err == nil && rep == nil {
|
||||
if rep == nil {
|
||||
return []byte{agentSuccess}
|
||||
}
|
||||
|
||||
@@ -203,6 +203,9 @@ func parseConstraints(constraints []byte) (lifetimeSecs uint32, confirmBeforeUse
|
||||
for len(constraints) != 0 {
|
||||
switch constraints[0] {
|
||||
case agentConstrainLifetime:
|
||||
if len(constraints) < 5 {
|
||||
return 0, false, nil, io.ErrUnexpectedEOF
|
||||
}
|
||||
lifetimeSecs = binary.BigEndian.Uint32(constraints[1:5])
|
||||
constraints = constraints[5:]
|
||||
case agentConstrainConfirm:
|
||||
@@ -237,13 +240,35 @@ func setConstraints(key *AddedKey, constraintBytes []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkRSAKeyParams enforces the same bounds as parseRSA in the ssh
|
||||
// package, and additionally caps the prime factors. Without this,
|
||||
// the rsa.PrivateKey built from an Add request would call Precompute()
|
||||
// on arbitrary inputs; the CRT coefficient recomputation is cubic in
|
||||
// |p| and can consume excessive CPU on oversized keys.
|
||||
func checkRSAKeyParams(N, E, P, Q *big.Int) error {
|
||||
if N.BitLen() > 8192 {
|
||||
return errors.New("agent: RSA modulus too large")
|
||||
}
|
||||
if P.BitLen() > 4096 || Q.BitLen() > 4096 {
|
||||
return errors.New("agent: RSA prime too large")
|
||||
}
|
||||
if E.BitLen() > 24 {
|
||||
return errors.New("agent: RSA public exponent too large")
|
||||
}
|
||||
e := E.Int64()
|
||||
if e < 3 || e&1 == 0 {
|
||||
return errors.New("agent: incorrect RSA public exponent")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseRSAKey(req []byte) (*AddedKey, error) {
|
||||
var k rsaKeyMsg
|
||||
if err := ssh.Unmarshal(req, &k); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if k.E.BitLen() > 30 {
|
||||
return nil, errors.New("agent: RSA public exponent too large")
|
||||
if err := checkRSAKeyParams(k.N, k.E, k.P, k.Q); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
priv := &rsa.PrivateKey{
|
||||
PublicKey: rsa.PublicKey{
|
||||
@@ -267,6 +292,9 @@ func parseEd25519Key(req []byte) (*AddedKey, error) {
|
||||
if err := ssh.Unmarshal(req, &k); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(k.Priv) != ed25519.PrivateKeySize {
|
||||
return nil, fmt.Errorf("agent: bad ED25519 key size: %d", len(k.Priv))
|
||||
}
|
||||
priv := ed25519.PrivateKey(k.Priv)
|
||||
|
||||
addedKey := &AddedKey{PrivateKey: &priv, Comment: k.Comments}
|
||||
@@ -333,6 +361,9 @@ func parseEd25519Cert(req []byte) (*AddedKey, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(k.Priv) != ed25519.PrivateKeySize {
|
||||
return nil, fmt.Errorf("agent: bad ED25519 key size: %d", len(k.Priv))
|
||||
}
|
||||
priv := ed25519.PrivateKey(k.Priv)
|
||||
cert, ok := pubKey.(*ssh.Certificate)
|
||||
if !ok {
|
||||
@@ -390,8 +421,8 @@ func parseRSACert(req []byte) (*AddedKey, error) {
|
||||
return nil, fmt.Errorf("agent: Unmarshal failed to parse public key: %v", err)
|
||||
}
|
||||
|
||||
if rsaPub.E.BitLen() > 30 {
|
||||
return nil, errors.New("agent: RSA public exponent too large")
|
||||
if err := checkRSAKeyParams(rsaPub.N, rsaPub.E, k.P, k.Q); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
priv := rsa.PrivateKey{
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"io"
|
||||
pseudorand "math/rand"
|
||||
"reflect"
|
||||
"strings"
|
||||
@@ -258,9 +259,47 @@ func TestParseConstraints(t *testing.T) {
|
||||
t.Errorf("got extension %v, want %v", extensions, expect)
|
||||
}
|
||||
|
||||
// Test Malformed Constraint
|
||||
_, _, _, err = parseConstraints([]byte{1})
|
||||
if err != io.ErrUnexpectedEOF {
|
||||
t.Errorf("got %v, want %v", err, io.ErrUnexpectedEOF)
|
||||
}
|
||||
|
||||
// Test Unknown Constraint
|
||||
_, _, _, err = parseConstraints([]byte{128})
|
||||
if err == nil || !strings.Contains(err.Error(), "unknown constraint") {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseEd25519KeyShortPanic(t *testing.T) {
|
||||
msg := ssh.Marshal(ed25519KeyMsg{
|
||||
Type: ssh.KeyAlgoED25519,
|
||||
Pub: []byte{1, 2, 3},
|
||||
Priv: []byte{1, 2, 3, 4, 5},
|
||||
})
|
||||
|
||||
a, b, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer a.Close()
|
||||
defer b.Close()
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- ServeAgent(NewKeyring(), a) }()
|
||||
|
||||
c := NewClient(b)
|
||||
_, err = c.(*client).call(msg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
keys, err := c.List()
|
||||
if err != nil {
|
||||
t.Fatalf("agent died: %v", err)
|
||||
}
|
||||
if len(keys) != 0 {
|
||||
t.Error("short ed25519 key was accepted into keyring")
|
||||
}
|
||||
}
|
||||
|
||||
+17
-1
@@ -348,6 +348,9 @@ func (c *CertChecker) CheckHostKey(addr string, remote net.Addr, key PublicKey)
|
||||
if cert.CertType != HostCert {
|
||||
return fmt.Errorf("ssh: certificate presented as a host key has type %d", cert.CertType)
|
||||
}
|
||||
if c.IsHostAuthority == nil {
|
||||
return errors.New("ssh: cannot verify certificate, IsHostAuthority not set")
|
||||
}
|
||||
if !c.IsHostAuthority(cert.SignatureKey, addr) {
|
||||
return fmt.Errorf("ssh: no authorities for hostname: %v", addr)
|
||||
}
|
||||
@@ -375,6 +378,9 @@ func (c *CertChecker) Authenticate(conn ConnMetadata, pubKey PublicKey) (*Permis
|
||||
if cert.CertType != UserCert {
|
||||
return nil, fmt.Errorf("ssh: cert has type %d", cert.CertType)
|
||||
}
|
||||
if c.IsUserAuthority == nil {
|
||||
return nil, errors.New("ssh: cannot verify certificate, IsUserAuthority not set")
|
||||
}
|
||||
if !c.IsUserAuthority(cert.SignatureKey) {
|
||||
return nil, fmt.Errorf("ssh: certificate signed by unrecognized authority")
|
||||
}
|
||||
@@ -438,7 +444,17 @@ func (c *CertChecker) CheckCert(principal string, cert *Certificate) error {
|
||||
if before := int64(cert.ValidBefore); cert.ValidBefore != uint64(CertTimeInfinity) && (unixNow >= before || before < 0) {
|
||||
return fmt.Errorf("ssh: cert has expired")
|
||||
}
|
||||
if err := cert.SignatureKey.Verify(cert.bytesForSigning(), cert.Signature); err != nil {
|
||||
// Match OpenSSH: the SK user-presence flag is never enforced on a
|
||||
// certificate's CA signature. OpenSSH calls sshkey_verify with
|
||||
// detailsp==NULL in sshkey.c:cert_parse, so the UP/UV flags are
|
||||
// not even extracted. The UP bit on a CA signature reflects the
|
||||
// CA operator's presence at signing time, which has no bearing on
|
||||
// whether the user being authenticated is present now; enforcing
|
||||
// it here would only break interop with certificates issued by
|
||||
// non-interactive SK CAs. skKeyWithoutUP is a no-op for non-SK
|
||||
// keys (the common case).
|
||||
caKey := skKeyWithoutUP(cert.SignatureKey)
|
||||
if err := caKey.Verify(cert.bytesForSigning(), cert.Signature); err != nil {
|
||||
return fmt.Errorf("ssh: certificate signature does not verify")
|
||||
}
|
||||
|
||||
|
||||
+102
-5
@@ -9,8 +9,10 @@ import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"net"
|
||||
"reflect"
|
||||
"testing"
|
||||
@@ -128,6 +130,103 @@ func TestValidateCert(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// signSKCert builds an SK-ECDSA signature over cert.bytesForSigning()
|
||||
// using caKey as the simulated hardware token. The SK signing flags
|
||||
// byte (UP bit and others) is caller-controlled so tests can exercise
|
||||
// the user-presence enforcement paths. caApp is the SK application
|
||||
// string (typically "ssh:").
|
||||
func signSKCert(t *testing.T, cert *Certificate, caKey *ecdsa.PrivateKey, caApp string, flags byte) {
|
||||
t.Helper()
|
||||
cert.SignatureKey = &skECDSAPublicKey{
|
||||
application: caApp,
|
||||
PublicKey: caKey.PublicKey,
|
||||
}
|
||||
cert.Nonce = make([]byte, 32)
|
||||
if _, err := rand.Read(cert.Nonce); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
h := sha256.New()
|
||||
h.Write([]byte(caApp))
|
||||
appDigest := h.Sum(nil)
|
||||
h.Reset()
|
||||
h.Write(cert.bytesForSigning())
|
||||
dataDigest := h.Sum(nil)
|
||||
|
||||
var counter uint32 = 1
|
||||
blob := struct {
|
||||
ApplicationDigest []byte `ssh:"rest"`
|
||||
Flags byte
|
||||
Counter uint32
|
||||
MessageDigest []byte `ssh:"rest"`
|
||||
}{appDigest, flags, counter, dataDigest}
|
||||
h.Reset()
|
||||
h.Write(Marshal(blob))
|
||||
digest := h.Sum(nil)
|
||||
|
||||
r, s, err := ecdsa.Sign(rand.Reader, caKey, digest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cert.Signature = &Signature{
|
||||
Format: KeyAlgoSKECDSA256,
|
||||
Blob: Marshal(struct{ R, S *big.Int }{r, s}),
|
||||
Rest: Marshal(struct {
|
||||
Flags byte
|
||||
Counter uint32
|
||||
}{flags, counter}),
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckCertSKAuthorityNoUPRequired pins the OpenSSH-parity
|
||||
// behavior of CertChecker.CheckCert for SK CA signatures: a
|
||||
// certificate signed by an SK CA that produced a UP=0 signature is
|
||||
// accepted, because the UP bit on a CA signature has no bearing on
|
||||
// the current user authentication (see sshkey.c:cert_parse, which
|
||||
// passes detailsp==NULL to sshkey_verify). Without this, certs issued
|
||||
// by non-interactive SK CAs would fail to verify.
|
||||
func TestCheckCertSKAuthorityNoUPRequired(t *testing.T) {
|
||||
caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
userKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
userPub, err := NewPublicKey(&userKey.PublicKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
mkCert := func(flags byte) *Certificate {
|
||||
c := &Certificate{
|
||||
CertType: UserCert,
|
||||
Key: userPub,
|
||||
ValidBefore: CertTimeInfinity,
|
||||
ValidPrincipals: []string{"user"},
|
||||
}
|
||||
signSKCert(t, c, caKey, "ssh:", flags)
|
||||
return c
|
||||
}
|
||||
|
||||
checker := CertChecker{
|
||||
IsUserAuthority: func(k PublicKey) bool {
|
||||
caSK := &skECDSAPublicKey{application: "ssh:", PublicKey: caKey.PublicKey}
|
||||
return bytes.Equal(k.Marshal(), caSK.Marshal())
|
||||
},
|
||||
}
|
||||
|
||||
// Both UP=0 and UP=1 CA signatures verify: UP is not enforced
|
||||
// here, matching OpenSSH.
|
||||
if err := checker.CheckCert("user", mkCert(0)); err != nil {
|
||||
t.Errorf("UP=0 CA signature must verify (OpenSSH parity): %v", err)
|
||||
}
|
||||
if err := checker.CheckCert("user", mkCert(flagUserPresence)); err != nil {
|
||||
t.Errorf("UP=1 CA signature must verify: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateCertTime(t *testing.T) {
|
||||
cert := Certificate{
|
||||
ValidPrincipals: []string{"user"},
|
||||
@@ -330,15 +429,13 @@ func TestCertTypes(t *testing.T) {
|
||||
go NewServerConn(c1, conf)
|
||||
|
||||
priv := m.signer
|
||||
if err != nil {
|
||||
t.Fatalf("error generating ssh pubkey: %v", err)
|
||||
}
|
||||
|
||||
cert := &Certificate{
|
||||
CertType: UserCert,
|
||||
Key: priv.PublicKey(),
|
||||
}
|
||||
cert.SignCert(rand.Reader, priv)
|
||||
if err := cert.SignCert(rand.Reader, priv); err != nil {
|
||||
t.Fatalf("error signing certificate: %v", err)
|
||||
}
|
||||
|
||||
certSigner, err := NewCertSigner(cert, priv)
|
||||
if err != nil {
|
||||
|
||||
+62
-6
@@ -11,6 +11,7 @@ import (
|
||||
"io"
|
||||
"log"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -131,11 +132,17 @@ func (r RejectionReason) String() string {
|
||||
return fmt.Sprintf("unknown reason %d", int(r))
|
||||
}
|
||||
|
||||
func min(a uint32, b int) uint32 {
|
||||
if a < uint32(b) {
|
||||
return a
|
||||
// minPayloadSize returns min(limit, length) clamped to a uint32. It is used
|
||||
// to compute the size of the next channel data packet from the remaining
|
||||
// payload. The comparison is done in int64 because length is an int — on
|
||||
// 64-bit systems len(data) can exceed 2^32, and a direct uint32(length)
|
||||
// cast would silently truncate to 0 at every multiple of 2^32, causing
|
||||
// WriteExtended's loop to spin without making progress.
|
||||
func minPayloadSize(limit uint32, length int) uint32 {
|
||||
if int64(length) > int64(limit) {
|
||||
return limit
|
||||
}
|
||||
return uint32(b)
|
||||
return uint32(length)
|
||||
}
|
||||
|
||||
type channelDirection uint8
|
||||
@@ -177,6 +184,12 @@ type channel struct {
|
||||
// with WantReply=true outstanding. This lock is held by a
|
||||
// goroutine that has such an outgoing request pending.
|
||||
sentRequestMu sync.Mutex
|
||||
// sentRequestPending is set to true while a SendRequest call with
|
||||
// WantReply=true is in flight. handlePacket uses it as a gate: responses
|
||||
// arriving while no request is pending are dropped to prevent a
|
||||
// misbehaving peer from stalling the mux read loop by filling ch.msg
|
||||
// with unsolicited channelRequestSuccess/Failure messages.
|
||||
sentRequestPending atomic.Bool
|
||||
|
||||
incomingRequests chan *Request
|
||||
|
||||
@@ -251,7 +264,7 @@ func (ch *channel) WriteExtended(data []byte, extendedCode uint32) (n int, err e
|
||||
ch.writeMu.Unlock()
|
||||
|
||||
for len(data) > 0 {
|
||||
space := min(ch.maxRemotePayload, len(data))
|
||||
space := minPayloadSize(ch.maxRemotePayload, len(data))
|
||||
if space, err = ch.remoteWin.reserve(space); err != nil {
|
||||
return n, err
|
||||
}
|
||||
@@ -460,6 +473,18 @@ func (ch *channel) handlePacket(packet []byte) error {
|
||||
}
|
||||
|
||||
ch.incomingRequests <- &req
|
||||
case *channelRequestSuccessMsg, *channelRequestFailureMsg:
|
||||
// Drop responses that arrive when no SendRequest is waiting, to
|
||||
// prevent a malicious peer from filling ch.msg and stalling the
|
||||
// mux read loop. The non-blocking send additionally protects the
|
||||
// loop if a well-behaved caller is slow to read.
|
||||
if !ch.sentRequestPending.Load() {
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
case ch.msg <- msg:
|
||||
default:
|
||||
}
|
||||
default:
|
||||
ch.msg <- msg
|
||||
}
|
||||
@@ -530,7 +555,17 @@ func (ch *channel) Reject(reason RejectionReason, message string) error {
|
||||
Language: "en",
|
||||
}
|
||||
ch.decided = true
|
||||
return ch.sendMessage(reject)
|
||||
err := ch.sendMessage(reject)
|
||||
|
||||
// Remove the channel from the mux to prevent memory leaks.
|
||||
// Do not call ch.close() here: no goroutine holds a reference to a
|
||||
// rejected channel's internal channels (msg, incomingRequests), so
|
||||
// removing it from chanList is sufficient for GC. Calling close()
|
||||
// would race with the mux loop goroutine (handlePacket or dropAll),
|
||||
// causing a panic from closing an already-closed channel.
|
||||
ch.mux.chanList.remove(ch.localId)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (ch *channel) Read(data []byte) (int, error) {
|
||||
@@ -586,6 +621,27 @@ func (ch *channel) SendRequest(name string, wantReply bool, payload []byte) (boo
|
||||
if wantReply {
|
||||
ch.sentRequestMu.Lock()
|
||||
defer ch.sentRequestMu.Unlock()
|
||||
|
||||
// Open the gate so that responses arriving while this request is in
|
||||
// flight are allowed to reach ch.msg. Responses arriving while no
|
||||
// request is pending are dropped by handlePacket.
|
||||
ch.sentRequestPending.Store(true)
|
||||
defer ch.sentRequestPending.Store(false)
|
||||
|
||||
// Drain any spurious responses that may have been buffered. This
|
||||
// prevents a previously buffered unexpected response from being
|
||||
// consumed instead of the actual response for this request.
|
||||
drain:
|
||||
for {
|
||||
select {
|
||||
case _, ok := <-ch.msg:
|
||||
if !ok {
|
||||
break drain
|
||||
}
|
||||
default:
|
||||
break drain
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
msg := channelRequestMsg{
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
// Copyright 2025 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"math/bits"
|
||||
"testing"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func TestMinPayloadSize(t *testing.T) {
|
||||
// 4 GiB (2^32). Declared as a var (not a const) so that int(bigPayload)
|
||||
// is a runtime conversion: a constant conversion would fail to compile
|
||||
// on 32-bit platforms with "constant 4294967296 overflows int". On
|
||||
// 32-bit the value truncates to 0 at runtime, but the is64Bit cases
|
||||
// that reference it are skipped by the runtime check below.
|
||||
var bigPayload int64 = 1 << 32
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
maxPayload uint32
|
||||
dataLen int
|
||||
want uint32
|
||||
is64Bit bool // Flag to run only on 64-bit architectures
|
||||
}{
|
||||
{
|
||||
name: "Normal Case - Data fits in payload",
|
||||
maxPayload: 32768,
|
||||
dataLen: 1000,
|
||||
want: 1000,
|
||||
},
|
||||
{
|
||||
name: "Normal Case - Data larger than payload",
|
||||
maxPayload: 32768,
|
||||
dataLen: 50000,
|
||||
want: 32768,
|
||||
},
|
||||
{
|
||||
name: "Boundary Case - Data zero",
|
||||
maxPayload: 32768,
|
||||
dataLen: 0,
|
||||
want: 0,
|
||||
},
|
||||
{
|
||||
name: "Overflow Case - Data is exactly 4GB (1<<32)",
|
||||
maxPayload: 32768,
|
||||
dataLen: int(bigPayload),
|
||||
want: 32768,
|
||||
is64Bit: true,
|
||||
},
|
||||
{
|
||||
name: "Overflow Case - Data is 4GB + small amount",
|
||||
maxPayload: 32768,
|
||||
dataLen: int(bigPayload + 100),
|
||||
want: 32768,
|
||||
is64Bit: true,
|
||||
},
|
||||
}
|
||||
|
||||
is64Bit := bits.UintSize == 64
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if tt.is64Bit && !is64Bit {
|
||||
t.Skip("Skipping test requiring 64-bit int")
|
||||
}
|
||||
got := minPayloadSize(tt.maxPayload, tt.dataLen)
|
||||
if got != tt.want {
|
||||
t.Errorf("minPayloadSize(%d, %d) = %d; want %d", tt.maxPayload, tt.dataLen, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteExtendedNoInfiniteLoopOnLargeWrite is an end-to-end regression
|
||||
// test for the integer-overflow bug in WriteExtended. Before the fix, a
|
||||
// write whose len(data) was a multiple of 2^32 caused minPayloadSize to
|
||||
// return 0; WriteExtended then spun forever, reserving 0 bytes per
|
||||
// iteration and never advancing the data slice.
|
||||
//
|
||||
// We exercise the real WriteExtended path with a slice whose declared
|
||||
// length is exactly 2^32. Allocating 4 GiB is unnecessary: each iteration
|
||||
// only reads up to maxRemotePayload bytes from the head of the slice, and
|
||||
// the loop blocks in remoteWin.reserve() once the channel window is
|
||||
// exhausted — before the slice base advances past the underlying buffer.
|
||||
//
|
||||
// With the fix, the loop blocks in reserve(); we detect that via
|
||||
// waitWriterBlocked(), then close the window to let WriteExtended return.
|
||||
// With the bug, the loop never blocks and the test times out.
|
||||
//
|
||||
//go:nocheckptr
|
||||
func TestWriteExtendedNoInfiniteLoopOnLargeWrite(t *testing.T) {
|
||||
if bits.UintSize < 64 {
|
||||
t.Skip("test requires 64-bit int to construct a slice with len >= 2^32")
|
||||
}
|
||||
|
||||
reader, writer, mux := channelPair(t)
|
||||
defer reader.Close()
|
||||
defer writer.Close()
|
||||
defer mux.Close()
|
||||
|
||||
// Sized to hold the full pre-update remote window so that no iteration
|
||||
// reads past the backing buffer before reserve() blocks.
|
||||
backing := make([]byte, channelWindowSize)
|
||||
var bigLen int64 = 1 << 32
|
||||
bigSlice := unsafe.Slice(&backing[0], int(bigLen))
|
||||
|
||||
done := make(chan int, 1)
|
||||
go func() {
|
||||
n, _ := writer.Write(bigSlice)
|
||||
done <- n
|
||||
}()
|
||||
|
||||
blocked := make(chan struct{})
|
||||
go func() {
|
||||
writer.remoteWin.waitWriterBlocked()
|
||||
close(blocked)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-blocked:
|
||||
// Good — the loop made progress and is now blocked in reserve().
|
||||
// Close the window to let WriteExtended return.
|
||||
writer.remoteWin.close()
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("WriteExtended did not block in reserve within 2s — minPayloadSize likely returned 0 (integer overflow regression)")
|
||||
}
|
||||
|
||||
select {
|
||||
case n := <-done:
|
||||
if n == 0 {
|
||||
t.Fatalf("WriteExtended returned n=0; expected progress")
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("WriteExtended did not return after closing the window")
|
||||
}
|
||||
}
|
||||
+31
-29
@@ -8,6 +8,7 @@ import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/des"
|
||||
"crypto/fips140"
|
||||
"crypto/rc4"
|
||||
"crypto/subtle"
|
||||
"encoding/binary"
|
||||
@@ -15,6 +16,7 @@ import (
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"slices"
|
||||
|
||||
"golang.org/x/crypto/chacha20"
|
||||
"golang.org/x/crypto/internal/poly1305"
|
||||
@@ -93,41 +95,41 @@ func streamCipherMode(skip int, createFunc func(key, iv []byte) (cipher.Stream,
|
||||
}
|
||||
|
||||
// cipherModes documents properties of supported ciphers. Ciphers not included
|
||||
// are not supported and will not be negotiated, even if explicitly requested in
|
||||
// ClientConfig.Crypto.Ciphers.
|
||||
var cipherModes = map[string]*cipherMode{
|
||||
// Ciphers from RFC 4344, which introduced many CTR-based ciphers. Algorithms
|
||||
// are defined in the order specified in the RFC.
|
||||
CipherAES128CTR: {16, aes.BlockSize, streamCipherMode(0, newAESCTR)},
|
||||
CipherAES192CTR: {24, aes.BlockSize, streamCipherMode(0, newAESCTR)},
|
||||
CipherAES256CTR: {32, aes.BlockSize, streamCipherMode(0, newAESCTR)},
|
||||
// are not supported and will not be negotiated, even if explicitly configured.
|
||||
// When FIPS mode is enabled, only FIPS-approved algorithms are included.
|
||||
var cipherModes = map[string]*cipherMode{}
|
||||
|
||||
// Ciphers from RFC 4345, which introduces security-improved arcfour ciphers.
|
||||
// They are defined in the order specified in the RFC.
|
||||
InsecureCipherRC4128: {16, 0, streamCipherMode(1536, newRC4)},
|
||||
InsecureCipherRC4256: {32, 0, streamCipherMode(1536, newRC4)},
|
||||
func init() {
|
||||
cipherModes[CipherAES128CTR] = &cipherMode{16, aes.BlockSize, streamCipherMode(0, newAESCTR)}
|
||||
cipherModes[CipherAES192CTR] = &cipherMode{24, aes.BlockSize, streamCipherMode(0, newAESCTR)}
|
||||
cipherModes[CipherAES256CTR] = &cipherMode{32, aes.BlockSize, streamCipherMode(0, newAESCTR)}
|
||||
// Use of GCM with arbitrary IVs is not allowed in FIPS 140-only mode,
|
||||
// we'll wire it up to NewGCMForSSH in Go 1.26.
|
||||
//
|
||||
// For now it means we'll work with fips140=on but not fips140=only.
|
||||
cipherModes[CipherAES128GCM] = &cipherMode{16, 12, newGCMCipher}
|
||||
cipherModes[CipherAES256GCM] = &cipherMode{32, 12, newGCMCipher}
|
||||
|
||||
// Cipher defined in RFC 4253, which describes SSH Transport Layer Protocol.
|
||||
// Note that this cipher is not safe, as stated in RFC 4253: "Arcfour (and
|
||||
// RC4) has problems with weak keys, and should be used with caution."
|
||||
// RFC 4345 introduces improved versions of Arcfour.
|
||||
InsecureCipherRC4: {16, 0, streamCipherMode(0, newRC4)},
|
||||
|
||||
// AEAD ciphers
|
||||
CipherAES128GCM: {16, 12, newGCMCipher},
|
||||
CipherAES256GCM: {32, 12, newGCMCipher},
|
||||
CipherChaCha20Poly1305: {64, 0, newChaCha20Cipher},
|
||||
if fips140.Enabled() {
|
||||
defaultCiphers = slices.DeleteFunc(defaultCiphers, func(algo string) bool {
|
||||
_, ok := cipherModes[algo]
|
||||
return !ok
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
cipherModes[CipherChaCha20Poly1305] = &cipherMode{64, 0, newChaCha20Cipher}
|
||||
// Insecure ciphers not included in the default configuration.
|
||||
cipherModes[InsecureCipherRC4128] = &cipherMode{16, 0, streamCipherMode(1536, newRC4)}
|
||||
cipherModes[InsecureCipherRC4256] = &cipherMode{32, 0, streamCipherMode(1536, newRC4)}
|
||||
cipherModes[InsecureCipherRC4] = &cipherMode{16, 0, streamCipherMode(0, newRC4)}
|
||||
// CBC mode is insecure and so is not included in the default config.
|
||||
// (See https://www.ieee-security.org/TC/SP2013/papers/4977a526.pdf). If absolutely
|
||||
// needed, it's possible to specify a custom Config to enable it.
|
||||
// You should expect that an active attacker can recover plaintext if
|
||||
// you do.
|
||||
InsecureCipherAES128CBC: {16, aes.BlockSize, newAESCBCCipher},
|
||||
|
||||
// 3des-cbc is insecure and is not included in the default
|
||||
// config.
|
||||
InsecureCipherTripleDESCBC: {24, des.BlockSize, newTripleDESCBCCipher},
|
||||
cipherModes[InsecureCipherAES128CBC] = &cipherMode{16, aes.BlockSize, newAESCBCCipher}
|
||||
cipherModes[InsecureCipherTripleDESCBC] = &cipherMode{24, des.BlockSize, newTripleDESCBCCipher}
|
||||
}
|
||||
|
||||
// prefixLen is the length of the packet prefix that contains the packet length
|
||||
@@ -405,7 +407,7 @@ func (c *gcmCipher) readCipherPacket(seqNum uint32, r io.Reader) ([]byte, error)
|
||||
return nil, fmt.Errorf("ssh: illegal padding %d", padding)
|
||||
}
|
||||
|
||||
if int(padding+1) >= len(plain) {
|
||||
if int(padding)+1 >= len(plain) {
|
||||
return nil, fmt.Errorf("ssh: padding %d too large", padding)
|
||||
}
|
||||
plain = plain[1 : length-uint32(padding)]
|
||||
@@ -584,7 +586,7 @@ func (c *cbcCipher) writeCipherPacket(seqNum uint32, w io.Writer, rand io.Reader
|
||||
|
||||
// Length of encrypted portion of the packet (header, payload, padding).
|
||||
// Enforce minimum padding and packet size.
|
||||
encLength := maxUInt32(prefixLen+len(packet)+cbcMinPaddingSize, cbcMinPaddingSize)
|
||||
encLength := maxUInt32(prefixLen+len(packet)+cbcMinPaddingSize, cbcMinPacketSize)
|
||||
// Enforce block size.
|
||||
encLength = (encLength + effectiveBlockSize - 1) / effectiveBlockSize * effectiveBlockSize
|
||||
|
||||
|
||||
@@ -88,6 +88,32 @@ func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan
|
||||
return conn, conn.mux.incomingChannels, conn.mux.incomingRequests, nil
|
||||
}
|
||||
|
||||
// NewControlClientConn establishes an SSH connection over an OpenSSH
|
||||
// ControlMaster socket c in proxy mode.
|
||||
//
|
||||
// Note that this package only implements the client side of the multiplexing
|
||||
// protocol. The provided net.Conn must be a local, secure connection (such as a
|
||||
// Unix domain socket) connected to an already-running OpenSSH process acting as
|
||||
// the ControlMaster.
|
||||
//
|
||||
// WARNING: Because proxy mode bypasses the standard cryptographic handshake
|
||||
// passing a standard network connection (e.g., TCP) will result in plaintext
|
||||
// data leakage.
|
||||
//
|
||||
// The Request and NewChannel channels must be serviced or the connection
|
||||
// will hang.
|
||||
func NewControlClientConn(c net.Conn) (Conn, <-chan NewChannel, <-chan *Request, error) {
|
||||
conn := &connection{
|
||||
sshConn: sshConn{conn: c},
|
||||
}
|
||||
var err error
|
||||
if conn.transport, err = handshakeControlProxy(c); err != nil {
|
||||
return nil, nil, nil, fmt.Errorf("ssh: control proxy handshake failed: %w", err)
|
||||
}
|
||||
conn.mux = newMux(conn.transport)
|
||||
return conn, conn.mux.incomingChannels, conn.mux.incomingRequests, nil
|
||||
}
|
||||
|
||||
// clientHandshake performs the client side key exchange. See RFC 4253 Section
|
||||
// 7.
|
||||
func (c *connection) clientHandshake(dialAddress string, config *ClientConfig) error {
|
||||
@@ -197,6 +223,59 @@ type HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
|
||||
// the server. A BannerCallback receives the message sent by the remote server.
|
||||
type BannerCallback func(message string) error
|
||||
|
||||
// ClientAuthContext contains information about the current state of the
|
||||
// authentication process, passed to [ClientAuthCallback].
|
||||
type ClientAuthContext struct {
|
||||
// Metadata contains the connection metadata.
|
||||
Metadata ConnMetadata
|
||||
|
||||
// Algorithms contains the negotiated algorithms.
|
||||
Algorithms NegotiatedAlgorithms
|
||||
|
||||
// AllowedMethods lists the authentication methods currently accepted
|
||||
// by the server. These are the protocol-level names defined in RFC 4252
|
||||
// such as "publickey", "password".
|
||||
AllowedMethods []string
|
||||
|
||||
// PartialSuccessMethods lists the authentication methods that have already
|
||||
// succeeded, indicating a multi-step authentication flow. This list
|
||||
// represents the exact sequence of partial successes and may contain
|
||||
// duplicates if the same method succeeded multiple times.
|
||||
PartialSuccessMethods []string
|
||||
|
||||
// TriedMethods lists the methods that have already been attempted and
|
||||
// failed during this session. This list represents the exact sequence of
|
||||
// failures and may contain duplicates. This allows the callback to also
|
||||
// track the number of failed attempts for a specific method.
|
||||
TriedMethods []string
|
||||
}
|
||||
|
||||
// ClientAuthCallback is a hook invoked before each authentication attempt. It
|
||||
// allows the client to dynamically select an authentication method based on the
|
||||
// current context, server capabilities, or previous failures.
|
||||
//
|
||||
// The callback is invoked after the initial "none" authentication method, once
|
||||
// the server's supported authentication methods are known.
|
||||
//
|
||||
// Return values:
|
||||
// - (AuthMethod, nil): The client will attempt this specific method next.
|
||||
// The returned method does NOT need to be present in [ClientConfig.Auth].
|
||||
// This allows for dynamic authentication strategies (e.g., prompting
|
||||
// for a password only if public key auth fails). Callers should inspect
|
||||
// [ClientAuthContext.TriedMethods] to avoid repeatedly returning the
|
||||
// same failing method.
|
||||
// - (nil, nil): The client selects from [ClientConfig.Auth] the first
|
||||
// instance of a method that has not been tried yet, or aborts if none
|
||||
// are left. If authentication is not successful, the callback is invoked
|
||||
// again before the following attempt.
|
||||
// - (nil, error): The authentication process is aborted immediately,
|
||||
// causing the ongoing SSH handshake to fail with the provided error.
|
||||
//
|
||||
// To bound resource use, the client caps the total number of authentication
|
||||
// attempts (failures and partial successes combined) at 64. If the cap is
|
||||
// exceeded the handshake aborts with an error.
|
||||
type ClientAuthCallback func(ctx *ClientAuthContext) (AuthMethod, error)
|
||||
|
||||
// A ClientConfig structure is used to configure a Client. It must not be
|
||||
// modified after having been passed to an SSH function.
|
||||
type ClientConfig struct {
|
||||
@@ -210,6 +289,9 @@ type ClientConfig struct {
|
||||
// Auth contains possible authentication methods to use with the
|
||||
// server. Only the first instance of a particular RFC 4252 method will
|
||||
// be used during authentication.
|
||||
//
|
||||
// If AuthCallback is set, these AuthMethod are only used if the
|
||||
// callback returns nil.
|
||||
Auth []AuthMethod
|
||||
|
||||
// HostKeyCallback is called during the cryptographic
|
||||
@@ -240,6 +322,9 @@ type ClientConfig struct {
|
||||
//
|
||||
// A Timeout of zero means no timeout.
|
||||
Timeout time.Duration
|
||||
|
||||
// AuthCallback, if non-nil, is invoked before each authentication attempt.
|
||||
AuthCallback ClientAuthCallback
|
||||
}
|
||||
|
||||
// InsecureIgnoreHostKey returns a function that can be used for
|
||||
|
||||
+62
-30
@@ -9,6 +9,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -20,6 +21,12 @@ const (
|
||||
authSuccess
|
||||
)
|
||||
|
||||
// maxAuthClientTried bounds the total number of authentication attempts
|
||||
// (failures and partial successes combined) the client makes before
|
||||
// aborting the loop, to prevent unbounded growth when an AuthCallback
|
||||
// keeps supplying methods.
|
||||
const maxAuthClientTried = 64
|
||||
|
||||
// clientAuthenticate authenticates with the remote server. See RFC 4252.
|
||||
func (c *connection) clientAuthenticate(config *ClientConfig) error {
|
||||
// initiate user auth session
|
||||
@@ -66,38 +73,68 @@ func (c *connection) clientAuthenticate(config *ClientConfig) error {
|
||||
// then any untried methods suggested by the server.
|
||||
var tried []string
|
||||
var lastMethods []string
|
||||
var partialSuccess []string
|
||||
|
||||
sessionID := c.transport.getSessionID()
|
||||
for auth := AuthMethod(new(noneAuth)); auth != nil; {
|
||||
ok, methods, err := auth.auth(sessionID, config.User, c.transport, config.Rand, extensions)
|
||||
if err != nil {
|
||||
// On disconnect, return error immediately
|
||||
if _, ok := err.(*disconnectMsg); ok {
|
||||
if _, isDisconnect := err.(*disconnectMsg); isDisconnect {
|
||||
return err
|
||||
}
|
||||
// We return the error later if there is no other method left to
|
||||
// try.
|
||||
// We return the error later if there is no other method
|
||||
// left to try.
|
||||
ok = authFailure
|
||||
}
|
||||
if ok == authSuccess {
|
||||
// success
|
||||
|
||||
switch ok {
|
||||
case authSuccess:
|
||||
return nil
|
||||
} else if ok == authFailure {
|
||||
if m := auth.method(); !contains(tried, m) {
|
||||
tried = append(tried, m)
|
||||
}
|
||||
case authPartialSuccess:
|
||||
partialSuccess = append(partialSuccess, auth.method())
|
||||
case authFailure:
|
||||
tried = append(tried, auth.method())
|
||||
}
|
||||
if len(partialSuccess)+len(tried) > maxAuthClientTried {
|
||||
return fmt.Errorf("ssh: too many authentication attempts (%d), aborting",
|
||||
len(partialSuccess)+len(tried))
|
||||
}
|
||||
|
||||
if methods == nil {
|
||||
methods = lastMethods
|
||||
}
|
||||
lastMethods = methods
|
||||
|
||||
// If AuthCallback is set it takes precedence: it picks the next
|
||||
// AuthMethod dynamically. The returned method need not be in
|
||||
// config.Auth. If the callback returns (nil, nil) we fall back to
|
||||
// selecting the next untried method from config.Auth below; on
|
||||
// (nil, error) the handshake aborts.
|
||||
if config.AuthCallback != nil {
|
||||
ctx := &ClientAuthContext{
|
||||
Metadata: c,
|
||||
Algorithms: c.Algorithms(),
|
||||
AllowedMethods: slices.Clone(methods),
|
||||
PartialSuccessMethods: slices.Clone(partialSuccess),
|
||||
TriedMethods: slices.Clone(tried),
|
||||
}
|
||||
altAuth, cbErr := config.AuthCallback(ctx)
|
||||
if cbErr != nil {
|
||||
return cbErr
|
||||
}
|
||||
if altAuth != nil {
|
||||
auth = altAuth
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
auth = nil
|
||||
|
||||
findNext:
|
||||
for _, a := range config.Auth {
|
||||
candidateMethod := a.method()
|
||||
if contains(tried, candidateMethod) {
|
||||
if slices.Contains(tried, candidateMethod) {
|
||||
continue
|
||||
}
|
||||
for _, meth := range methods {
|
||||
@@ -117,15 +154,6 @@ func (c *connection) clientAuthenticate(config *ClientConfig) error {
|
||||
return fmt.Errorf("ssh: unable to authenticate, attempted methods %v, no supported methods remain", tried)
|
||||
}
|
||||
|
||||
func contains(list []string, e string) bool {
|
||||
for _, s := range list {
|
||||
if s == e {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// An AuthMethod represents an instance of an RFC 4252 authentication method.
|
||||
type AuthMethod interface {
|
||||
// auth authenticates user over transport t.
|
||||
@@ -255,7 +283,7 @@ func pickSignatureAlgorithm(signer Signer, extensions map[string][]byte) (MultiA
|
||||
// Fallback to use if there is no "server-sig-algs" extension or a
|
||||
// common algorithm cannot be found. We use the public key format if the
|
||||
// MultiAlgorithmSigner supports it, otherwise we return an error.
|
||||
if !contains(as.Algorithms(), underlyingAlgo(keyFormat)) {
|
||||
if !slices.Contains(as.Algorithms(), underlyingAlgo(keyFormat)) {
|
||||
return "", fmt.Errorf("ssh: no common public key signature algorithm, server only supports %q for key type %q, signer only supports %v",
|
||||
underlyingAlgo(keyFormat), keyFormat, as.Algorithms())
|
||||
}
|
||||
@@ -282,10 +310,14 @@ func pickSignatureAlgorithm(signer Signer, extensions map[string][]byte) (MultiA
|
||||
}
|
||||
|
||||
// Filter algorithms based on those supported by MultiAlgorithmSigner.
|
||||
// Iterate over the signer's algorithms first to preserve its preference order.
|
||||
supportedKeyAlgos := algorithmsForKeyFormat(keyFormat)
|
||||
var keyAlgos []string
|
||||
for _, algo := range algorithmsForKeyFormat(keyFormat) {
|
||||
if contains(as.Algorithms(), underlyingAlgo(algo)) {
|
||||
keyAlgos = append(keyAlgos, algo)
|
||||
for _, signerAlgo := range as.Algorithms() {
|
||||
if idx := slices.IndexFunc(supportedKeyAlgos, func(algo string) bool {
|
||||
return underlyingAlgo(algo) == signerAlgo
|
||||
}); idx >= 0 {
|
||||
keyAlgos = append(keyAlgos, supportedKeyAlgos[idx])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -334,7 +366,7 @@ func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand
|
||||
// the key try to use the obtained algorithm as if "server-sig-algs" had
|
||||
// not been implemented if supported from the algorithm signer.
|
||||
if !ok && idx < origSignersLen && isRSACert(algo) && algo != CertAlgoRSAv01 {
|
||||
if contains(as.Algorithms(), KeyAlgoRSA) {
|
||||
if slices.Contains(as.Algorithms(), KeyAlgoRSA) {
|
||||
// We retry using the compat algorithm after all signers have
|
||||
// been tried normally.
|
||||
signers = append(signers, &multiAlgorithmSigner{
|
||||
@@ -381,11 +413,11 @@ func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand
|
||||
return authFailure, nil, err
|
||||
}
|
||||
|
||||
// If authentication succeeds or the list of available methods does not
|
||||
// contain the "publickey" method, do not attempt to authenticate with any
|
||||
// other keys. According to RFC 4252 Section 7, the latter can occur when
|
||||
// additional authentication methods are required.
|
||||
if success == authSuccess || !contains(methods, cb.method()) {
|
||||
// If authentication succeeds or partially succeeds, return immediately
|
||||
// so the caller can select the next auth method. According to RFC 4252
|
||||
// Section 7, if the server no longer lists "publickey" among its
|
||||
// allowed methods, do not attempt to authenticate with any other keys.
|
||||
if success == authSuccess || success == authPartialSuccess || !slices.Contains(methods, cb.method()) {
|
||||
return success, methods, err
|
||||
}
|
||||
}
|
||||
@@ -434,7 +466,7 @@ func confirmKeyAck(key PublicKey, c packetConn) (bool, error) {
|
||||
// servers send the key type instead. OpenSSH allows any algorithm
|
||||
// that matches the public key, so we do the same.
|
||||
// https://github.com/openssh/openssh-portable/blob/86bdd385/sshconnect2.c#L709
|
||||
if !contains(algorithmsForKeyFormat(key.Type()), msg.Algo) {
|
||||
if !slices.Contains(algorithmsForKeyFormat(key.Type()), msg.Algo) {
|
||||
return false, nil
|
||||
}
|
||||
if !bytes.Equal(msg.PubKey, pubKey) {
|
||||
|
||||
+800
-2
@@ -14,6 +14,7 @@ import (
|
||||
"net"
|
||||
"os"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
@@ -168,6 +169,689 @@ func TestClientAuthThirdKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// partialSuccessPublicKeyAndKbdInteractiveServer returns a server config
|
||||
// where the rsa key gets partial success and the server offers both publickey
|
||||
// and keyboard-interactive as next methods. The VerifiedPublicKeyCallback
|
||||
// tracks state so that the same key only triggers partial success once,
|
||||
// avoiding an impossible auth loop.
|
||||
func partialSuccessPublicKeyAndKbdInteractiveServer() *ServerConfig {
|
||||
rsaDone := false
|
||||
serverConf := &ServerConfig{
|
||||
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
|
||||
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
},
|
||||
VerifiedPublicKeyCallback: func(conn ConnMetadata, key PublicKey, permissions *Permissions, signatureAlgorithm string) (*Permissions, error) {
|
||||
if !rsaDone && bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
|
||||
rsaDone = true
|
||||
return nil, &PartialSuccessError{
|
||||
Next: ServerAuthCallbacks{
|
||||
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
|
||||
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
},
|
||||
KeyboardInteractiveCallback: func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error) {
|
||||
answers, err := client("", "", []string{"token: "}, []bool{true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(answers) == 1 && answers[0] == "correct-token" {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.New("invalid token")
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
},
|
||||
}
|
||||
serverConf.AddHostKey(testSigners["rsa"])
|
||||
return serverConf
|
||||
}
|
||||
|
||||
// partialSuccessMultiKeyServer returns a server config that requires two
|
||||
// public keys in sequence: the first key (rsa) triggers partial success
|
||||
// requiring a second key (ecdsa) to complete authentication.
|
||||
func partialSuccessMultiKeyServer() *ServerConfig {
|
||||
firstKeyDone := false
|
||||
serverConf := &ServerConfig{
|
||||
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
|
||||
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
|
||||
return nil, nil
|
||||
}
|
||||
if bytes.Equal(key.Marshal(), testPublicKeys["ecdsa"].Marshal()) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
},
|
||||
VerifiedPublicKeyCallback: func(conn ConnMetadata, key PublicKey, permissions *Permissions, signatureAlgorithm string) (*Permissions, error) {
|
||||
if !firstKeyDone && bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
|
||||
firstKeyDone = true
|
||||
return nil, &PartialSuccessError{
|
||||
Next: ServerAuthCallbacks{
|
||||
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
|
||||
if bytes.Equal(key.Marshal(), testPublicKeys["ecdsa"].Marshal()) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
if firstKeyDone && bytes.Equal(key.Marshal(), testPublicKeys["ecdsa"].Marshal()) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
},
|
||||
}
|
||||
serverConf.AddHostKey(testSigners["rsa"])
|
||||
return serverConf
|
||||
}
|
||||
|
||||
func TestStaticMultiKeyPartialSuccess(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
clientConf := &ClientConfig{
|
||||
User: "user",
|
||||
Auth: []AuthMethod{
|
||||
PublicKeys(testSigners["rsa"], testSigners["ecdsa"]),
|
||||
},
|
||||
HostKeyCallback: InsecureIgnoreHostKey(),
|
||||
}
|
||||
|
||||
go NewServerConn(c1, partialSuccessMultiKeyServer())
|
||||
|
||||
_, _, _, err = NewClientConn(c2, "", clientConf)
|
||||
if err != nil {
|
||||
t.Fatalf("client login error: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaticPartialSuccess(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
clientConf := &ClientConfig{
|
||||
User: "user",
|
||||
Auth: []AuthMethod{
|
||||
PublicKeys(testSigners["rsa"]),
|
||||
KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
|
||||
return []string{"correct-token"}, nil
|
||||
}),
|
||||
},
|
||||
HostKeyCallback: InsecureIgnoreHostKey(),
|
||||
}
|
||||
|
||||
go NewServerConn(c1, partialSuccessPublicKeyAndKbdInteractiveServer())
|
||||
|
||||
_, _, _, err = NewClientConn(c2, "", clientConf)
|
||||
if err != nil {
|
||||
t.Fatalf("client login error: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// partialSuccessKeyAThenKeyBServer returns a server config where keyA (rsa)
|
||||
// gets partial success and the server offers BOTH publickey and
|
||||
// keyboard-interactive. keyB (ecdsa) then completes auth successfully.
|
||||
func partialSuccessKeyAThenKeyBServer() *ServerConfig {
|
||||
keyADone := false
|
||||
serverConf := &ServerConfig{
|
||||
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
|
||||
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
|
||||
return nil, nil
|
||||
}
|
||||
if bytes.Equal(key.Marshal(), testPublicKeys["ecdsa"].Marshal()) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
},
|
||||
VerifiedPublicKeyCallback: func(conn ConnMetadata, key PublicKey, permissions *Permissions, signatureAlgorithm string) (*Permissions, error) {
|
||||
if !keyADone && bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
|
||||
keyADone = true
|
||||
return nil, &PartialSuccessError{
|
||||
Next: ServerAuthCallbacks{
|
||||
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
|
||||
if bytes.Equal(key.Marshal(), testPublicKeys["ecdsa"].Marshal()) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
},
|
||||
KeyboardInteractiveCallback: func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error) {
|
||||
answers, err := client("", "", []string{"token: "}, []bool{true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(answers) == 1 && answers[0] == "correct-token" {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.New("invalid token")
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
if keyADone && bytes.Equal(key.Marshal(), testPublicKeys["ecdsa"].Marshal()) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
},
|
||||
}
|
||||
serverConf.AddHostKey(testSigners["rsa"])
|
||||
return serverConf
|
||||
}
|
||||
|
||||
func TestStaticPartialSuccessKeyAThenKeyB(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
clientConf := &ClientConfig{
|
||||
User: "user",
|
||||
Auth: []AuthMethod{
|
||||
PublicKeys(testSigners["rsa"], testSigners["ecdsa"]),
|
||||
},
|
||||
HostKeyCallback: InsecureIgnoreHostKey(),
|
||||
}
|
||||
|
||||
go NewServerConn(c1, partialSuccessKeyAThenKeyBServer())
|
||||
|
||||
_, _, _, err = NewClientConn(c2, "", clientConf)
|
||||
if err != nil {
|
||||
t.Fatalf("client login error: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// partialSuccessMultiKeyThenKbdInteractiveServer returns a server config
|
||||
// that strictly requires keyA (rsa) AND keyB (ecdsa) as public keys before
|
||||
// allowing keyboard-interactive. After keyA, ONLY publickey is offered
|
||||
// (for keyB). After keyB, ONLY keyboard-interactive is offered.
|
||||
func partialSuccessMultiKeyThenKbdInteractiveServer() *ServerConfig {
|
||||
serverConf := &ServerConfig{
|
||||
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
|
||||
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
|
||||
return nil, &PartialSuccessError{
|
||||
Next: ServerAuthCallbacks{
|
||||
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
|
||||
if bytes.Equal(key.Marshal(), testPublicKeys["ecdsa"].Marshal()) {
|
||||
return nil, &PartialSuccessError{
|
||||
Next: ServerAuthCallbacks{
|
||||
KeyboardInteractiveCallback: func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error) {
|
||||
answers, err := client("", "", []string{"token: "}, []bool{true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(answers) == 1 && answers[0] == "correct-token" {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.New("invalid token")
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
},
|
||||
}
|
||||
serverConf.AddHostKey(testSigners["rsa"])
|
||||
return serverConf
|
||||
}
|
||||
|
||||
func TestStaticMultiKeyPartialThenKbdInteractive(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
clientConf := &ClientConfig{
|
||||
User: "user",
|
||||
Auth: []AuthMethod{
|
||||
PublicKeys(testSigners["rsa"], testSigners["ecdsa"]),
|
||||
KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
|
||||
return []string{"correct-token"}, nil
|
||||
}),
|
||||
},
|
||||
HostKeyCallback: InsecureIgnoreHostKey(),
|
||||
}
|
||||
|
||||
go NewServerConn(c1, partialSuccessMultiKeyThenKbdInteractiveServer())
|
||||
|
||||
_, _, _, err = NewClientConn(c2, "", clientConf)
|
||||
if err != nil {
|
||||
t.Fatalf("client login error: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthMethodDynamic(t *testing.T) {
|
||||
config := &ClientConfig{
|
||||
User: "testuser",
|
||||
Auth: nil,
|
||||
HostKeyCallback: InsecureIgnoreHostKey(),
|
||||
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
|
||||
if len(ctx.Metadata.SessionID()) == 0 {
|
||||
t.Error("empty sessionID")
|
||||
}
|
||||
if ctx.Algorithms.HostKey == "" {
|
||||
t.Error("empty Host Key")
|
||||
}
|
||||
if slices.Contains(ctx.AllowedMethods, "password") {
|
||||
return Password(clientPassword), nil
|
||||
}
|
||||
return nil, errors.New("auth callback error")
|
||||
},
|
||||
}
|
||||
|
||||
if err := tryAuth(t, config); err != nil {
|
||||
t.Fatalf("unable to dial remote side: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCallbackError(t *testing.T) {
|
||||
config := &ClientConfig{
|
||||
User: "testuser",
|
||||
Auth: []AuthMethod{
|
||||
Password(clientPassword),
|
||||
},
|
||||
HostKeyCallback: InsecureIgnoreHostKey(),
|
||||
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
|
||||
return nil, errors.New("auth callback error")
|
||||
},
|
||||
}
|
||||
|
||||
if err := tryAuth(t, config); err == nil {
|
||||
t.Fatal("authentication unexpectedly succeeded after AuthCallback returned an error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCallbackPartialSuccess(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
clientConf := &ClientConfig{
|
||||
User: "user",
|
||||
HostKeyCallback: InsecureIgnoreHostKey(),
|
||||
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
|
||||
if slices.Contains(ctx.AllowedMethods, "publickey") && !slices.Contains(ctx.PartialSuccessMethods, "publickey") {
|
||||
return PublicKeys(testSigners["rsa"]), nil
|
||||
}
|
||||
if slices.Contains(ctx.PartialSuccessMethods, "publickey") && slices.Contains(ctx.AllowedMethods, "keyboard-interactive") {
|
||||
return KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
|
||||
return []string{"correct-token"}, nil
|
||||
}), nil
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected auth state: allowed=%v partial=%v", ctx.AllowedMethods, ctx.PartialSuccessMethods)
|
||||
},
|
||||
}
|
||||
|
||||
go NewServerConn(c1, partialSuccessPublicKeyAndKbdInteractiveServer())
|
||||
|
||||
_, _, _, err = NewClientConn(c2, "", clientConf)
|
||||
if err != nil {
|
||||
t.Fatalf("client login error: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCallbackMultiKeyPartialSuccess(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
clientConf := &ClientConfig{
|
||||
User: "user",
|
||||
HostKeyCallback: InsecureIgnoreHostKey(),
|
||||
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
|
||||
if slices.Contains(ctx.AllowedMethods, "publickey") && !slices.Contains(ctx.PartialSuccessMethods, "publickey") {
|
||||
return PublicKeys(testSigners["rsa"]), nil
|
||||
}
|
||||
if slices.Contains(ctx.PartialSuccessMethods, "publickey") && slices.Contains(ctx.AllowedMethods, "publickey") {
|
||||
return PublicKeys(testSigners["ecdsa"]), nil
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected auth state: allowed=%v partial=%v", ctx.AllowedMethods, ctx.PartialSuccessMethods)
|
||||
},
|
||||
}
|
||||
|
||||
go NewServerConn(c1, partialSuccessMultiKeyServer())
|
||||
|
||||
_, _, _, err = NewClientConn(c2, "", clientConf)
|
||||
if err != nil {
|
||||
t.Fatalf("client login error: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCallbackMultiKeyPartialThenKbdInteractive(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
clientConf := &ClientConfig{
|
||||
User: "user",
|
||||
HostKeyCallback: InsecureIgnoreHostKey(),
|
||||
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
|
||||
partialCount := len(ctx.PartialSuccessMethods)
|
||||
if partialCount == 0 && slices.Contains(ctx.AllowedMethods, "publickey") {
|
||||
return PublicKeys(testSigners["rsa"]), nil
|
||||
}
|
||||
if partialCount == 1 && slices.Contains(ctx.AllowedMethods, "publickey") {
|
||||
return PublicKeys(testSigners["ecdsa"]), nil
|
||||
}
|
||||
if partialCount >= 2 && slices.Contains(ctx.AllowedMethods, "keyboard-interactive") {
|
||||
return KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
|
||||
return []string{"correct-token"}, nil
|
||||
}), nil
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected auth state: allowed=%v partial=%v tried=%v",
|
||||
ctx.AllowedMethods, ctx.PartialSuccessMethods, ctx.TriedMethods)
|
||||
},
|
||||
}
|
||||
|
||||
go NewServerConn(c1, partialSuccessMultiKeyThenKbdInteractiveServer())
|
||||
|
||||
_, _, _, err = NewClientConn(c2, "", clientConf)
|
||||
if err != nil {
|
||||
t.Fatalf("client login error: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCallbackPartialSuccessKeyAThenKeyB(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
clientConf := &ClientConfig{
|
||||
User: "user",
|
||||
HostKeyCallback: InsecureIgnoreHostKey(),
|
||||
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
|
||||
if len(ctx.PartialSuccessMethods) == 0 && slices.Contains(ctx.AllowedMethods, "publickey") {
|
||||
return PublicKeys(testSigners["rsa"]), nil
|
||||
}
|
||||
if len(ctx.PartialSuccessMethods) == 1 && slices.Contains(ctx.AllowedMethods, "publickey") {
|
||||
return PublicKeys(testSigners["ecdsa"]), nil
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected auth state: allowed=%v partial=%v",
|
||||
ctx.AllowedMethods, ctx.PartialSuccessMethods)
|
||||
},
|
||||
}
|
||||
|
||||
go NewServerConn(c1, partialSuccessKeyAThenKeyBServer())
|
||||
|
||||
_, _, _, err = NewClientConn(c2, "", clientConf)
|
||||
if err != nil {
|
||||
t.Fatalf("client login error: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCallbackPartialSuccessWithStaticAuth(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
clientConf := &ClientConfig{
|
||||
User: "user",
|
||||
Auth: []AuthMethod{
|
||||
PublicKeys(testSigners["rsa"]),
|
||||
},
|
||||
HostKeyCallback: InsecureIgnoreHostKey(),
|
||||
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
|
||||
if slices.Contains(ctx.PartialSuccessMethods, "publickey") && slices.Contains(ctx.AllowedMethods, "keyboard-interactive") {
|
||||
return KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
|
||||
return []string{"correct-token"}, nil
|
||||
}), nil
|
||||
}
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
|
||||
go NewServerConn(c1, partialSuccessPublicKeyAndKbdInteractiveServer())
|
||||
|
||||
_, _, _, err = NewClientConn(c2, "", clientConf)
|
||||
if err != nil {
|
||||
t.Fatalf("client login error: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func partialSuccessPubKeyForbiddenAfterPartialServer(maxTries int) *ServerConfig {
|
||||
serverConf := &ServerConfig{
|
||||
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
|
||||
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
},
|
||||
VerifiedPublicKeyCallback: func(conn ConnMetadata, key PublicKey, permissions *Permissions, signatureAlgorithm string) (*Permissions, error) {
|
||||
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
|
||||
return nil, &PartialSuccessError{
|
||||
Next: ServerAuthCallbacks{
|
||||
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
|
||||
return nil, errors.New("legacy public key authentication is forbidden")
|
||||
},
|
||||
KeyboardInteractiveCallback: func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error) {
|
||||
answers, err := client("", "", []string{"token: "}, []bool{true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(answers) == 1 && answers[0] == "correct-token" {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.New("invalid token")
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
return nil, errors.New("invalid credentials")
|
||||
},
|
||||
MaxAuthTries: maxTries,
|
||||
}
|
||||
serverConf.AddHostKey(testSigners["rsa"])
|
||||
return serverConf
|
||||
}
|
||||
|
||||
func TestAuthCallbackPartialSuccessWithStaticMultiKey(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
clientConf := &ClientConfig{
|
||||
User: "user",
|
||||
Auth: []AuthMethod{
|
||||
PublicKeys(
|
||||
testSigners["rsa"],
|
||||
testSigners["ecdsa"],
|
||||
testSigners["ed25519"],
|
||||
),
|
||||
},
|
||||
HostKeyCallback: InsecureIgnoreHostKey(),
|
||||
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
|
||||
if slices.Contains(ctx.PartialSuccessMethods, "publickey") && slices.Contains(ctx.AllowedMethods, "keyboard-interactive") {
|
||||
return KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
|
||||
return []string{"correct-token"}, nil
|
||||
}), nil
|
||||
}
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
|
||||
go NewServerConn(c1, partialSuccessPubKeyForbiddenAfterPartialServer(2))
|
||||
|
||||
_, _, _, err = NewClientConn(c2, "", clientConf)
|
||||
if err != nil {
|
||||
t.Fatalf("client login error: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCallbackPartialSuccessShortCircuit(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
serverConf := partialSuccessPubKeyForbiddenAfterPartialServer(2)
|
||||
|
||||
pubkeyAttempts := 0
|
||||
clientConf := &ClientConfig{
|
||||
User: "user",
|
||||
HostKeyCallback: InsecureIgnoreHostKey(),
|
||||
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
|
||||
if slices.Contains(ctx.AllowedMethods, "publickey") && !slices.Contains(ctx.PartialSuccessMethods, "publickey") {
|
||||
pubkeyAttempts++
|
||||
return PublicKeys(testSigners["rsa"], testSigners["ecdsa"], testSigners["ed25519"]), nil
|
||||
}
|
||||
if slices.Contains(ctx.PartialSuccessMethods, "publickey") && slices.Contains(ctx.AllowedMethods, "keyboard-interactive") {
|
||||
return KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
|
||||
return []string{"correct-token"}, nil
|
||||
}), nil
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected auth state: allowed=%v partial=%v tried=%v",
|
||||
ctx.AllowedMethods, ctx.PartialSuccessMethods, ctx.TriedMethods)
|
||||
},
|
||||
}
|
||||
|
||||
go NewServerConn(c1, serverConf)
|
||||
|
||||
_, _, _, err = NewClientConn(c2, "", clientConf)
|
||||
if err != nil {
|
||||
t.Fatalf("client login error: %s", err)
|
||||
}
|
||||
if pubkeyAttempts != 1 {
|
||||
t.Errorf("expected publickey to be attempted once before short-circuit, got %d", pubkeyAttempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCallbackTriedLoopBound(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
serverConf := &ServerConfig{
|
||||
MaxAuthTries: -1,
|
||||
PasswordCallback: func(conn ConnMetadata, pass []byte) (*Permissions, error) {
|
||||
return nil, errors.New("password rejected")
|
||||
},
|
||||
}
|
||||
serverConf.AddHostKey(testSigners["rsa"])
|
||||
|
||||
invocations := 0
|
||||
clientConf := &ClientConfig{
|
||||
User: "user",
|
||||
HostKeyCallback: InsecureIgnoreHostKey(),
|
||||
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
|
||||
invocations++
|
||||
return Password("wrong"), nil
|
||||
},
|
||||
}
|
||||
|
||||
go NewServerConn(c1, serverConf)
|
||||
|
||||
_, _, _, err = NewClientConn(c2, "", clientConf)
|
||||
if err == nil {
|
||||
t.Fatal("expected the client to abort after exceeding the attempts cap")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "too many authentication attempts") {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
if invocations != maxAuthClientTried {
|
||||
t.Errorf("AuthCallback invoked %d times; expected %d",
|
||||
invocations, maxAuthClientTried)
|
||||
}
|
||||
}
|
||||
|
||||
func alwaysPartialPubKeyServer() *ServerConfig {
|
||||
var alwaysPartial func(ConnMetadata, PublicKey) (*Permissions, error)
|
||||
alwaysPartial = func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
|
||||
if !bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
|
||||
return nil, errors.New("invalid credentials")
|
||||
}
|
||||
return nil, &PartialSuccessError{
|
||||
Next: ServerAuthCallbacks{
|
||||
PublicKeyCallback: alwaysPartial,
|
||||
},
|
||||
}
|
||||
}
|
||||
serverConf := &ServerConfig{
|
||||
MaxAuthTries: -1,
|
||||
PublicKeyCallback: alwaysPartial,
|
||||
}
|
||||
serverConf.AddHostKey(testSigners["rsa"])
|
||||
return serverConf
|
||||
}
|
||||
|
||||
func TestAuthCallbackPartialSuccessLoopBound(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
invocations := 0
|
||||
clientConf := &ClientConfig{
|
||||
User: "user",
|
||||
HostKeyCallback: InsecureIgnoreHostKey(),
|
||||
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
|
||||
invocations++
|
||||
return PublicKeys(testSigners["rsa"]), nil
|
||||
},
|
||||
}
|
||||
|
||||
go NewServerConn(c1, alwaysPartialPubKeyServer())
|
||||
|
||||
_, _, _, err = NewClientConn(c2, "", clientConf)
|
||||
if err == nil {
|
||||
t.Fatal("expected the client to abort after exceeding the attempts cap")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "too many authentication attempts") {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
if invocations != maxAuthClientTried {
|
||||
t.Errorf("AuthCallback invoked %d times; expected %d",
|
||||
invocations, maxAuthClientTried)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthMethodPassword(t *testing.T) {
|
||||
config := &ClientConfig{
|
||||
User: "testuser",
|
||||
@@ -970,6 +1654,74 @@ func TestAuthMethodGSSAPIWithMIC(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
type maliciousGSSAPIWithMICAuthMethod struct{}
|
||||
|
||||
func (maliciousGSSAPIWithMICAuthMethod) method() string {
|
||||
// Reuse an advertised auth method name so the client attempts this
|
||||
// AuthMethod even when gssapi-with-mic is not advertised.
|
||||
return "password"
|
||||
}
|
||||
|
||||
func (maliciousGSSAPIWithMICAuthMethod) auth(session []byte, user string, c packetConn, rand io.Reader, _ map[string][]byte) (authResult, []string, error) {
|
||||
req := &userAuthRequestMsg{
|
||||
User: user,
|
||||
Service: serviceSSH,
|
||||
Method: "gssapi-with-mic",
|
||||
}
|
||||
req.Payload = appendU32(req.Payload, 1)
|
||||
req.Payload = appendString(req.Payload, string(krb5OID))
|
||||
if err := c.writePacket(Marshal(req)); err != nil {
|
||||
return authFailure, nil, err
|
||||
}
|
||||
|
||||
packet, err := c.readPacket()
|
||||
if err != nil {
|
||||
return authFailure, nil, err
|
||||
}
|
||||
switch packet[0] {
|
||||
case msgUserAuthFailure:
|
||||
var msg userAuthFailureMsg
|
||||
if err := Unmarshal(packet, &msg); err != nil {
|
||||
return authFailure, nil, err
|
||||
}
|
||||
if msg.PartialSuccess {
|
||||
return authPartialSuccess, msg.Methods, nil
|
||||
}
|
||||
return authFailure, msg.Methods, nil
|
||||
default:
|
||||
return authFailure, nil, unexpectedMessageError(msgUserAuthFailure, packet[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestGSSAPIWithMICPartialConfigRejectedAtRuntime(t *testing.T) {
|
||||
config := &ClientConfig{
|
||||
User: "testuser",
|
||||
Auth: []AuthMethod{
|
||||
maliciousGSSAPIWithMICAuthMethod{},
|
||||
},
|
||||
HostKeyCallback: InsecureIgnoreHostKey(),
|
||||
}
|
||||
|
||||
clientErr, serverErrs := tryAuthBothSides(t, config, &GSSAPIWithMICConfig{
|
||||
Server: &FakeServer{},
|
||||
})
|
||||
|
||||
if clientErr == nil || !strings.Contains(clientErr.Error(), "ssh: unable to authenticate") {
|
||||
t.Fatalf("client got %v, want authentication failure", clientErr)
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, err := range serverErrs {
|
||||
if err != nil && strings.Contains(err.Error(), "ssh: gssapi-with-mic auth not configured") {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("server auth errors = %v, want gssapi-with-mic auth not configured", serverErrs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompatibleAlgoAndSignatures(t *testing.T) {
|
||||
type testcase struct {
|
||||
algo string
|
||||
@@ -1135,7 +1887,7 @@ func TestPickSignatureAlgorithm(t *testing.T) {
|
||||
t.Fatalf("error generating cert signer: %v", err)
|
||||
}
|
||||
// The signer supports the public key algorithm and the
|
||||
// public key format is a certificate type so the cerificate
|
||||
// public key format is a certificate type so the certificate
|
||||
// algorithm matching the key format must be returned
|
||||
_, algo, err = pickSignatureAlgorithm(certSigner, c.extensions)
|
||||
if err != nil {
|
||||
@@ -1158,6 +1910,52 @@ func TestPickSignatureAlgorithm(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPickSignatureAlgorithmRespectsSignerPreference(t *testing.T) {
|
||||
algoSigner, ok := testSigners["rsa"].(AlgorithmSigner)
|
||||
if !ok {
|
||||
t.Fatalf("rsa test signer does not implement the AlgorithmSigner interface")
|
||||
}
|
||||
|
||||
serverExtensions := map[string][]byte{
|
||||
"server-sig-algs": []byte(KeyAlgoRSASHA256 + "," + KeyAlgoRSASHA512),
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
signerPrefs []string
|
||||
expectedAlgo string
|
||||
}{
|
||||
{
|
||||
name: "Signer prefers SHA512 then SHA256",
|
||||
signerPrefs: []string{KeyAlgoRSASHA512, KeyAlgoRSASHA256},
|
||||
expectedAlgo: KeyAlgoRSASHA512,
|
||||
},
|
||||
{
|
||||
name: "Signer prefers SHA256 then SHA512",
|
||||
signerPrefs: []string{KeyAlgoRSASHA256, KeyAlgoRSASHA512},
|
||||
expectedAlgo: KeyAlgoRSASHA256,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
orderedSigner, err := NewSignerWithAlgorithms(algoSigner, tc.signerPrefs)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create ordered signer: %v", err)
|
||||
}
|
||||
|
||||
_, selectedAlgo, err := pickSignatureAlgorithm(orderedSigner, serverExtensions)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if selectedAlgo != tc.expectedAlgo {
|
||||
t.Errorf("Algorithm mismatch; got %q want %q", selectedAlgo, tc.expectedAlgo)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// configurablePublicKeyCallback is a public key callback that allows to
|
||||
// configure the signature algorithm and format. This way we can emulate the
|
||||
// behavior of buggy clients.
|
||||
@@ -1214,7 +2012,7 @@ func (cb configurablePublicKeyCallback) auth(session []byte, user string, c pack
|
||||
if err != nil {
|
||||
return authFailure, nil, err
|
||||
}
|
||||
if success == authSuccess || !contains(methods, cb.method()) {
|
||||
if success == authSuccess || !slices.Contains(methods, cb.method()) {
|
||||
return success, methods, err
|
||||
}
|
||||
|
||||
|
||||
+68
-17
@@ -6,6 +6,7 @@ package ssh
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/fips140"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -83,6 +84,7 @@ var (
|
||||
// supportedKexAlgos specifies key-exchange algorithms implemented by this
|
||||
// package in preference order, excluding those with security issues.
|
||||
supportedKexAlgos = []string{
|
||||
KeyExchangeMLKEM768X25519,
|
||||
KeyExchangeCurve25519,
|
||||
KeyExchangeECDHP256,
|
||||
KeyExchangeECDHP384,
|
||||
@@ -94,6 +96,7 @@ var (
|
||||
// defaultKexAlgos specifies the default preference for key-exchange
|
||||
// algorithms in preference order.
|
||||
defaultKexAlgos = []string{
|
||||
KeyExchangeMLKEM768X25519,
|
||||
KeyExchangeCurve25519,
|
||||
KeyExchangeECDHP256,
|
||||
KeyExchangeECDHP384,
|
||||
@@ -254,6 +257,40 @@ type Algorithms struct {
|
||||
PublicKeyAuths []string
|
||||
}
|
||||
|
||||
func init() {
|
||||
if fips140.Enabled() {
|
||||
defaultHostKeyAlgos = slices.DeleteFunc(defaultHostKeyAlgos, func(algo string) bool {
|
||||
_, err := hashFunc(underlyingAlgo(algo))
|
||||
return err != nil
|
||||
})
|
||||
defaultPubKeyAuthAlgos = slices.DeleteFunc(defaultPubKeyAuthAlgos, func(algo string) bool {
|
||||
_, err := hashFunc(underlyingAlgo(algo))
|
||||
return err != nil
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func hashFunc(format string) (crypto.Hash, error) {
|
||||
switch format {
|
||||
case KeyAlgoRSASHA256, KeyAlgoECDSA256, KeyAlgoSKED25519, KeyAlgoSKECDSA256:
|
||||
return crypto.SHA256, nil
|
||||
case KeyAlgoECDSA384:
|
||||
return crypto.SHA384, nil
|
||||
case KeyAlgoRSASHA512, KeyAlgoECDSA521:
|
||||
return crypto.SHA512, nil
|
||||
case KeyAlgoED25519:
|
||||
// KeyAlgoED25519 doesn't pre-hash.
|
||||
return 0, nil
|
||||
case KeyAlgoRSA, InsecureKeyAlgoDSA:
|
||||
if fips140.Enabled() {
|
||||
return 0, fmt.Errorf("ssh: hash algorithm for format %q not allowed in FIPS 140 mode", format)
|
||||
}
|
||||
return crypto.SHA1, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("ssh: hash algorithm for format %q not mapped", format)
|
||||
}
|
||||
}
|
||||
|
||||
// SupportedAlgorithms returns algorithms currently implemented by this package,
|
||||
// excluding those with security issues, which are returned by
|
||||
// InsecureAlgorithms. The algorithms listed here are in preference order.
|
||||
@@ -281,21 +318,6 @@ func InsecureAlgorithms() Algorithms {
|
||||
|
||||
var supportedCompressions = []string{compressionNone}
|
||||
|
||||
// hashFuncs keeps the mapping of supported signature algorithms to their
|
||||
// respective hashes needed for signing and verification.
|
||||
var hashFuncs = map[string]crypto.Hash{
|
||||
KeyAlgoRSA: crypto.SHA1,
|
||||
KeyAlgoRSASHA256: crypto.SHA256,
|
||||
KeyAlgoRSASHA512: crypto.SHA512,
|
||||
InsecureKeyAlgoDSA: crypto.SHA1,
|
||||
KeyAlgoECDSA256: crypto.SHA256,
|
||||
KeyAlgoECDSA384: crypto.SHA384,
|
||||
KeyAlgoECDSA521: crypto.SHA512,
|
||||
// KeyAlgoED25519 doesn't pre-hash.
|
||||
KeyAlgoSKECDSA256: crypto.SHA256,
|
||||
KeyAlgoSKED25519: crypto.SHA256,
|
||||
}
|
||||
|
||||
// algorithmsForKeyFormat returns the supported signature algorithms for a given
|
||||
// public key format (PublicKey.Type), in order of preference. See RFC 8332,
|
||||
// Section 2. See also the note in sendKexInit on backwards compatibility.
|
||||
@@ -310,11 +332,40 @@ func algorithmsForKeyFormat(keyFormat string) []string {
|
||||
}
|
||||
}
|
||||
|
||||
// keyFormatForAlgorithm returns the key format corresponding to the given
|
||||
// signature algorithm. It returns an empty string if the signature algorithm is
|
||||
// invalid or unsupported.
|
||||
func keyFormatForAlgorithm(sigAlgo string) string {
|
||||
switch sigAlgo {
|
||||
case KeyAlgoRSA, KeyAlgoRSASHA256, KeyAlgoRSASHA512:
|
||||
return KeyAlgoRSA
|
||||
case CertAlgoRSAv01, CertAlgoRSASHA256v01, CertAlgoRSASHA512v01:
|
||||
return CertAlgoRSAv01
|
||||
case KeyAlgoED25519,
|
||||
KeyAlgoSKED25519,
|
||||
KeyAlgoSKECDSA256,
|
||||
KeyAlgoECDSA256,
|
||||
KeyAlgoECDSA384,
|
||||
KeyAlgoECDSA521,
|
||||
InsecureKeyAlgoDSA,
|
||||
InsecureCertAlgoDSAv01,
|
||||
CertAlgoECDSA256v01,
|
||||
CertAlgoECDSA384v01,
|
||||
CertAlgoECDSA521v01,
|
||||
CertAlgoSKECDSA256v01,
|
||||
CertAlgoED25519v01,
|
||||
CertAlgoSKED25519v01:
|
||||
return sigAlgo
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// isRSA returns whether algo is a supported RSA algorithm, including certificate
|
||||
// algorithms.
|
||||
func isRSA(algo string) bool {
|
||||
algos := algorithmsForKeyFormat(KeyAlgoRSA)
|
||||
return contains(algos, underlyingAlgo(algo))
|
||||
return slices.Contains(algos, underlyingAlgo(algo))
|
||||
}
|
||||
|
||||
func isRSACert(algo string) bool {
|
||||
@@ -513,7 +564,7 @@ func (c *Config) SetDefaults() {
|
||||
if kexAlgoMap[k] != nil {
|
||||
// Ignore the KEX if we have no kexAlgoMap definition.
|
||||
kexs = append(kexs, k)
|
||||
if k == KeyExchangeCurve25519 && !contains(c.KeyExchanges, keyExchangeCurve25519LibSSH) {
|
||||
if k == KeyExchangeCurve25519 && !slices.Contains(c.KeyExchanges, keyExchangeCurve25519LibSSH) {
|
||||
kexs = append(kexs, keyExchangeCurve25519LibSSH)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"reflect"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -174,3 +176,21 @@ func TestFindAgreedAlgorithms(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyFormatAlgorithms(t *testing.T) {
|
||||
supportedAlgos := SupportedAlgorithms()
|
||||
insecureAlgos := InsecureAlgorithms()
|
||||
algoritms := append(supportedAlgos.PublicKeyAuths, insecureAlgos.PublicKeyAuths...)
|
||||
algoritms = append(algoritms, slices.Collect(maps.Keys(certKeyAlgoNames))...)
|
||||
|
||||
for _, algo := range algoritms {
|
||||
keyFormat := keyFormatForAlgorithm(algo)
|
||||
if keyFormat == "" {
|
||||
t.Errorf("got empty key format for algorithm %q", algo)
|
||||
}
|
||||
if !slices.Contains(algorithmsForKeyFormat(keyFormat), algo) {
|
||||
t.Errorf("algorithms for key format %q, does not contain %q", keyFormat, algo)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+9
-1
@@ -91,9 +91,17 @@ func DiscardRequests(in <-chan *Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// A connTransport represents the transport for a connection.
|
||||
type connTransport interface {
|
||||
packetConn
|
||||
getAlgorithms() NegotiatedAlgorithms
|
||||
getSessionID() []byte
|
||||
waitSession() error
|
||||
}
|
||||
|
||||
// A connection represents an incoming connection.
|
||||
type connection struct {
|
||||
transport *handshakeTransport
|
||||
transport connTransport
|
||||
sshConn
|
||||
|
||||
// The connection protocol.
|
||||
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
// Copyright 2026 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"golang.org/x/crypto/cryptobyte"
|
||||
)
|
||||
|
||||
const (
|
||||
muxProtocolVersion = 4
|
||||
|
||||
muxMsgHello = 0x00000001
|
||||
muxCProxy = 0x1000000f
|
||||
muxSProxy = 0x8000000f
|
||||
)
|
||||
|
||||
const controlProxyRequestID = 0
|
||||
|
||||
// handshakeControlProxy attempts to establish a transport connection with an
|
||||
// OpenSSH ControlMaster socket in proxy mode. For details see:
|
||||
// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.mux
|
||||
func handshakeControlProxy(rw io.ReadWriteCloser) (connTransport, error) {
|
||||
if err := controlProxyWritePacket(rw, func(b *cryptobyte.Builder) {
|
||||
b.AddUint32(muxMsgHello)
|
||||
b.AddUint32(muxProtocolVersion)
|
||||
}); err != nil {
|
||||
return nil, fmt.Errorf("mux hello write failed: %w", err)
|
||||
}
|
||||
if err := controlProxyWritePacket(rw, func(b *cryptobyte.Builder) {
|
||||
b.AddUint32(muxCProxy)
|
||||
b.AddUint32(controlProxyRequestID)
|
||||
}); err != nil {
|
||||
return nil, fmt.Errorf("mux client proxy write failed: %w", err)
|
||||
}
|
||||
|
||||
messageType, body, err := controlProxyReadMessage(rw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mux hello read failed: %w", err)
|
||||
}
|
||||
if messageType != muxMsgHello {
|
||||
return nil, fmt.Errorf("expected hello response, got %v", messageType)
|
||||
}
|
||||
var v uint32
|
||||
if !body.ReadUint32(&v) {
|
||||
return nil, errors.New("EOF reading mux protocol version")
|
||||
}
|
||||
if v != muxProtocolVersion {
|
||||
return nil, fmt.Errorf("mux server has unsupported version %v", v)
|
||||
}
|
||||
messageType, body, err = controlProxyReadMessage(rw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mux server proxy read failed: %w", err)
|
||||
}
|
||||
if messageType != muxSProxy {
|
||||
return nil, fmt.Errorf("expected server proxy response, got %v", messageType)
|
||||
}
|
||||
var reqID uint32
|
||||
if !body.ReadUint32(&reqID) {
|
||||
return nil, errors.New("EOF reading request id")
|
||||
}
|
||||
if reqID != controlProxyRequestID {
|
||||
return nil, fmt.Errorf("expected request id %v, got %v", controlProxyRequestID, reqID)
|
||||
}
|
||||
return &controlProxyTransport{rw}, nil
|
||||
}
|
||||
|
||||
// controlProxyTransport implements the connTransport interface for
|
||||
// ControlMaster connections. Each controlMessage has zero length padding and
|
||||
// no MAC.
|
||||
type controlProxyTransport struct {
|
||||
rw io.ReadWriteCloser
|
||||
}
|
||||
|
||||
func (p *controlProxyTransport) Close() error {
|
||||
return p.rw.Close()
|
||||
}
|
||||
|
||||
func (p *controlProxyTransport) writePacket(controlMessage []byte) error {
|
||||
return controlProxyWritePacket(p.rw, func(b *cryptobyte.Builder) {
|
||||
b.AddUint8(0) // Padding length.
|
||||
b.AddBytes(controlMessage)
|
||||
})
|
||||
}
|
||||
|
||||
func (p *controlProxyTransport) readPacket() ([]byte, error) {
|
||||
buf, err := controlProxyReadPacket(p.rw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ssh: error reading control message: %w", err)
|
||||
}
|
||||
// Discard the padding length.
|
||||
if len(buf) < 1 {
|
||||
return nil, errors.New("ssh: EOF reading padding length")
|
||||
}
|
||||
if buf[0] != 0 {
|
||||
return nil, errors.New("ssh: unexpected non-zero padding in control message")
|
||||
}
|
||||
return buf[1:], nil
|
||||
}
|
||||
|
||||
func (p *controlProxyTransport) getAlgorithms() NegotiatedAlgorithms {
|
||||
return NegotiatedAlgorithms{}
|
||||
}
|
||||
|
||||
func (p *controlProxyTransport) getSessionID() []byte {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *controlProxyTransport) waitSession() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func controlProxyWritePacket(w io.Writer, f cryptobyte.BuilderContinuation) error {
|
||||
var buf []byte
|
||||
b := cryptobyte.NewBuilder(buf)
|
||||
b.AddUint32LengthPrefixed(f)
|
||||
out, err := b.Bytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = w.Write(out)
|
||||
return err
|
||||
}
|
||||
|
||||
func controlProxyReadPacket(r io.Reader) (cryptobyte.String, error) {
|
||||
var l uint32
|
||||
if err := binary.Read(r, binary.BigEndian, &l); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if l > maxPacket {
|
||||
return nil, fmt.Errorf("message length %v exceeds maximum %v", l, maxPacket)
|
||||
}
|
||||
buf := make([]byte, l)
|
||||
if _, err := io.ReadFull(r, buf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
func controlProxyReadMessage(r io.Reader) (messageType uint32, body cryptobyte.String, err error) {
|
||||
body, err = controlProxyReadPacket(r)
|
||||
if err != nil {
|
||||
return 0, nil, fmt.Errorf("error reading message body: %w", err)
|
||||
}
|
||||
if !body.ReadUint32(&messageType) {
|
||||
return 0, nil, errors.New("EOF reading message type")
|
||||
}
|
||||
return messageType, body, nil
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
// Copyright 2026 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestControlClientHandshake(t *testing.T) {
|
||||
reqs := [][]byte{
|
||||
// Hello request.
|
||||
{0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04},
|
||||
// Client proxy request.
|
||||
{0x00, 0x00, 0x00, 0x08, 0x10, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00},
|
||||
}
|
||||
respsNormal := [][]byte{
|
||||
// Hello response.
|
||||
{0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04},
|
||||
// Server proxy response.
|
||||
{0x00, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00},
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
resps [][]byte
|
||||
expectedErr string
|
||||
}{
|
||||
{
|
||||
name: "normal handshake",
|
||||
resps: respsNormal,
|
||||
},
|
||||
{
|
||||
name: "length greater than max",
|
||||
resps: [][]byte{
|
||||
{0xff, 0xff, 0xff, 0xff},
|
||||
respsNormal[1],
|
||||
},
|
||||
expectedErr: "message length 4294967295 exceeds maximum",
|
||||
},
|
||||
{
|
||||
name: "missing hello response",
|
||||
resps: [][]byte{
|
||||
{},
|
||||
},
|
||||
expectedErr: "use of closed network connection",
|
||||
},
|
||||
{
|
||||
name: "hello response too short",
|
||||
resps: [][]byte{
|
||||
{0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00},
|
||||
respsNormal[1],
|
||||
},
|
||||
expectedErr: "EOF",
|
||||
},
|
||||
{
|
||||
name: "bad hello response type",
|
||||
resps: [][]byte{
|
||||
{0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04},
|
||||
respsNormal[1],
|
||||
},
|
||||
expectedErr: "expected hello response, got 0",
|
||||
},
|
||||
{
|
||||
name: "bad protocol version",
|
||||
resps: [][]byte{
|
||||
{0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00},
|
||||
respsNormal[1],
|
||||
},
|
||||
expectedErr: "mux server has unsupported version 0",
|
||||
},
|
||||
{
|
||||
name: "missing server proxy response",
|
||||
resps: [][]byte{
|
||||
respsNormal[0],
|
||||
},
|
||||
expectedErr: "use of closed network connection",
|
||||
},
|
||||
{
|
||||
name: "server proxy response too short",
|
||||
resps: [][]byte{
|
||||
respsNormal[0],
|
||||
{0x00, 0x00, 0x00, 0x06, 0x80, 0x00, 0x00, 0x0f, 0x00, 0x00},
|
||||
},
|
||||
expectedErr: "EOF",
|
||||
},
|
||||
{
|
||||
name: "bad server proxy response type",
|
||||
resps: [][]byte{
|
||||
respsNormal[0],
|
||||
{0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
|
||||
},
|
||||
expectedErr: "expected server proxy response, got 0",
|
||||
},
|
||||
{
|
||||
name: "bad request id",
|
||||
resps: [][]byte{
|
||||
respsNormal[0],
|
||||
{0x00, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x01},
|
||||
},
|
||||
expectedErr: "expected request id 0, got 1",
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
done := make(chan error, 1)
|
||||
|
||||
ok := func() bool {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
go func() {
|
||||
defer close(done)
|
||||
_, _, _, err := NewControlClientConn(c2)
|
||||
c2.Write([]byte{0}) // Dummy message to unblock the final read.
|
||||
done <- err
|
||||
}()
|
||||
|
||||
i := 0
|
||||
for ; i < len(reqs) && i < len(tt.resps); i++ {
|
||||
expected := reqs[i]
|
||||
buf := make([]byte, len(expected))
|
||||
if _, err := io.ReadFull(c1, buf); err != nil {
|
||||
t.Errorf("error reading message %d: %v", i+1, err)
|
||||
return false
|
||||
}
|
||||
if !bytes.Equal(buf, expected) {
|
||||
t.Errorf(
|
||||
"unexpected message %d: got %v, want %v",
|
||||
i+1, buf, expected,
|
||||
)
|
||||
return false
|
||||
}
|
||||
_, err = c1.Write(tt.resps[i])
|
||||
if err != nil {
|
||||
t.Errorf("error writing message %d: %v", i+1, err)
|
||||
return false
|
||||
}
|
||||
}
|
||||
// Wait for the next message so that the final response can be read.
|
||||
buf := make([]byte, 1)
|
||||
c1.Read(buf)
|
||||
return true
|
||||
}()
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
err := <-done
|
||||
if tt.expectedErr != "" {
|
||||
if err == nil || !strings.Contains(err.Error(), tt.expectedErr) {
|
||||
t.Fatalf("got err %q; want err containing %q", err, tt.expectedErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("got err %q; want no err", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestControlClientTransport(t *testing.T) {
|
||||
type response struct {
|
||||
status bool
|
||||
payload []byte
|
||||
err error
|
||||
}
|
||||
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
resp []byte
|
||||
respStatus bool
|
||||
respPayload []byte
|
||||
expectedErr string
|
||||
}{
|
||||
{
|
||||
name: "successful request",
|
||||
resp: []byte{0x00, 0x00, 0x00, 0x02, 0x00, 0x51},
|
||||
respStatus: true,
|
||||
},
|
||||
{
|
||||
name: "failed request",
|
||||
resp: []byte{0x00, 0x00, 0x00, 0x02, 0x00, 0x52},
|
||||
respStatus: false,
|
||||
},
|
||||
{
|
||||
name: "short response",
|
||||
resp: []byte{0x00, 0x00, 0x00, 0x00},
|
||||
expectedErr: "EOF",
|
||||
},
|
||||
{
|
||||
name: "response with payload",
|
||||
resp: []byte{0x00, 0x00, 0x00, 0x05, 0x00, 0x51, 0x01, 0x02, 0x03},
|
||||
respStatus: true,
|
||||
respPayload: []byte{1, 2, 3},
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c1, c2, err := netPipe()
|
||||
if err != nil {
|
||||
t.Fatalf("netPipe: %v", err)
|
||||
}
|
||||
defer c1.Close()
|
||||
defer c2.Close()
|
||||
|
||||
// Handshake responses.
|
||||
c1.Write([]byte{
|
||||
0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04,
|
||||
0x00, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00,
|
||||
})
|
||||
|
||||
conn, chans, reqs, err := NewControlClientConn(c2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := NewClient(conn, chans, reqs)
|
||||
|
||||
done := make(chan response, 1)
|
||||
go func() {
|
||||
defer close(done)
|
||||
status, payload, err := client.SendRequest("hello", true, nil)
|
||||
if err != nil {
|
||||
done <- response{err: err}
|
||||
return
|
||||
}
|
||||
done <- response{
|
||||
status: status,
|
||||
payload: payload,
|
||||
}
|
||||
}()
|
||||
|
||||
// Discard handshake.
|
||||
io.CopyN(io.Discard, c1, 24)
|
||||
|
||||
expectedReq := []byte{
|
||||
0x00, 0x00, 0x00, 0x0c, 0x00, 0x50,
|
||||
0x00, 0x00, 0x00, 0x05, 'h', 'e', 'l', 'l', 'o',
|
||||
0x01,
|
||||
}
|
||||
buf := make([]byte, len(expectedReq))
|
||||
if _, err := io.ReadFull(c1, buf); err != nil {
|
||||
t.Fatalf("reading request: %v", err)
|
||||
}
|
||||
if !bytes.Equal(buf, expectedReq) {
|
||||
t.Fatalf("got request %v; want %v", buf, expectedReq)
|
||||
}
|
||||
|
||||
c1.Write(tt.resp)
|
||||
|
||||
resp := <-done
|
||||
if tt.expectedErr != "" {
|
||||
if resp.err == nil || !strings.Contains(resp.err.Error(), tt.expectedErr) {
|
||||
t.Fatalf("got err %q; want err containing %q", resp.err, tt.expectedErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if resp.err != nil {
|
||||
t.Fatalf("got err %q; want no err", resp.err)
|
||||
}
|
||||
if resp.status != tt.respStatus {
|
||||
t.Fatalf("got status %v; want %v", resp.status, tt.respStatus)
|
||||
}
|
||||
if !bytes.Equal(resp.payload, tt.respPayload) {
|
||||
t.Errorf("got payload %v; want %v", resp.payload, tt.respPayload)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+10
@@ -17,8 +17,18 @@ References:
|
||||
[PROTOCOL.certkeys]: http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.certkeys?rev=HEAD
|
||||
[SSH-PARAMETERS]: http://www.iana.org/assignments/ssh-parameters/ssh-parameters.xml#ssh-parameters-1
|
||||
[SSH-CERTS]: https://datatracker.ietf.org/doc/html/draft-miller-ssh-cert-01
|
||||
[FIPS 140-3 mode]: https://go.dev/doc/security/fips140
|
||||
|
||||
This package does not fall under the stability promise of the Go language itself,
|
||||
so its API may be changed when pressing needs arise.
|
||||
|
||||
# FIPS 140-3 mode
|
||||
|
||||
When the program is in [FIPS 140-3 mode], this package behaves as if only SP
|
||||
800-140C and SP 800-140D approved cipher suites, signature algorithms,
|
||||
certificate public key types and sizes, and key exchange and derivation
|
||||
algorithms were implemented. Others are silently ignored and not negotiated, or
|
||||
rejected. This set may depend on the algorithms supported by the FIPS 140-3 Go
|
||||
Cryptographic Module selected with GOFIPS140, and may change across Go versions.
|
||||
*/
|
||||
package ssh
|
||||
|
||||
+3
-3
@@ -155,7 +155,7 @@ func ExampleNewServerConn() {
|
||||
}
|
||||
|
||||
func ExampleServerConfig() {
|
||||
// Minimal ServerConfig with SHA-1 algoritms disabled and supporting only
|
||||
// Minimal ServerConfig with SHA-1 algorithms disabled and supporting only
|
||||
// public key authentication.
|
||||
|
||||
// The algorithms returned by ssh.SupportedAlgorithms() are different from
|
||||
@@ -344,7 +344,7 @@ func ExampleClientConfig() {
|
||||
log.Fatalf("unable to parse private key: %v", err)
|
||||
}
|
||||
|
||||
// Minimal ClientConfig with SHA-1 algoritms disabled.
|
||||
// Minimal ClientConfig with SHA-1 algorithms disabled.
|
||||
// The algorithms returned by ssh.SupportedAlgorithms() are different from
|
||||
// the default ones and do not include algorithms that are considered
|
||||
// insecure, such as those using SHA-1, returned by
|
||||
@@ -361,7 +361,7 @@ func ExampleClientConfig() {
|
||||
ssh.PublicKeys(signer),
|
||||
},
|
||||
HostKeyCallback: ssh.FixedHostKey(hostKey),
|
||||
// We should check that hostKey algorithm is inlcuded in
|
||||
// We should check that hostKey algorithm is included in
|
||||
// algorithms.HostKeys.
|
||||
HostKeyAlgorithms: algorithms.HostKeys,
|
||||
}
|
||||
|
||||
+5
-4
@@ -10,6 +10,7 @@ import (
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
@@ -527,7 +528,7 @@ func (t *handshakeTransport) sendKexInit() error {
|
||||
switch s := k.(type) {
|
||||
case MultiAlgorithmSigner:
|
||||
for _, algo := range algorithmsForKeyFormat(keyFormat) {
|
||||
if contains(s.Algorithms(), underlyingAlgo(algo)) {
|
||||
if slices.Contains(s.Algorithms(), underlyingAlgo(algo)) {
|
||||
msg.ServerHostKeyAlgos = append(msg.ServerHostKeyAlgos, algo)
|
||||
}
|
||||
}
|
||||
@@ -679,7 +680,7 @@ func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if t.sessionID == nil && ((isClient && contains(serverInit.KexAlgos, kexStrictServer)) || (!isClient && contains(clientInit.KexAlgos, kexStrictClient))) {
|
||||
if t.sessionID == nil && ((isClient && slices.Contains(serverInit.KexAlgos, kexStrictServer)) || (!isClient && slices.Contains(clientInit.KexAlgos, kexStrictClient))) {
|
||||
t.strictMode = true
|
||||
if err := t.conn.setStrictMode(); err != nil {
|
||||
return err
|
||||
@@ -736,7 +737,7 @@ func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error {
|
||||
// On the server side, after the first SSH_MSG_NEWKEYS, send a SSH_MSG_EXT_INFO
|
||||
// message with the server-sig-algs extension if the client supports it. See
|
||||
// RFC 8308, Sections 2.4 and 3.1, and [PROTOCOL], Section 1.9.
|
||||
if !isClient && firstKeyExchange && contains(clientInit.KexAlgos, "ext-info-c") {
|
||||
if !isClient && firstKeyExchange && slices.Contains(clientInit.KexAlgos, "ext-info-c") {
|
||||
supportedPubKeyAuthAlgosList := strings.Join(t.publicKeyAuthAlgorithms, ",")
|
||||
extInfo := &extInfoMsg{
|
||||
NumExtensions: 2,
|
||||
@@ -790,7 +791,7 @@ func (a algorithmSignerWrapper) SignWithAlgorithm(rand io.Reader, data []byte, a
|
||||
func pickHostKey(hostKeys []Signer, algo string) AlgorithmSigner {
|
||||
for _, k := range hostKeys {
|
||||
if s, ok := k.(MultiAlgorithmSigner); ok {
|
||||
if !contains(s.Algorithms(), underlyingAlgo(algo)) {
|
||||
if !slices.Contains(s.Algorithms(), underlyingAlgo(algo)) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1330,7 +1330,7 @@ func TestAlgorithmNegotiationError(t *testing.T) {
|
||||
|
||||
_, _, _, err = NewClientConn(c2, "", clientConf)
|
||||
if err == nil {
|
||||
t.Fatal("client connection succeded expected algorithm negotiation error")
|
||||
t.Fatal("client connection succeeded expected algorithm negotiation error")
|
||||
}
|
||||
var negotiationError *AlgorithmNegotiationError
|
||||
if !errors.As(err, &negotiationError) {
|
||||
|
||||
+100
-29
@@ -8,13 +8,15 @@ import (
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/fips140"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"slices"
|
||||
"sync"
|
||||
|
||||
"golang.org/x/crypto/curve25519"
|
||||
)
|
||||
@@ -396,9 +398,27 @@ func ecHash(curve elliptic.Curve) crypto.Hash {
|
||||
return crypto.SHA512
|
||||
}
|
||||
|
||||
// kexAlgoMap defines the supported KEXs. KEXs not included are not supported
|
||||
// and will not be negotiated, even if explicitly configured. When FIPS mode is
|
||||
// enabled, only FIPS-approved algorithms are included.
|
||||
var kexAlgoMap = map[string]kexAlgorithm{}
|
||||
|
||||
func init() {
|
||||
// mlkem768x25519-sha256 we'll work with fips140=on but not fips140=only
|
||||
// until Go 1.26.
|
||||
kexAlgoMap[KeyExchangeMLKEM768X25519] = &mlkem768WithCurve25519sha256{}
|
||||
kexAlgoMap[KeyExchangeECDHP521] = &ecdh{elliptic.P521()}
|
||||
kexAlgoMap[KeyExchangeECDHP384] = &ecdh{elliptic.P384()}
|
||||
kexAlgoMap[KeyExchangeECDHP256] = &ecdh{elliptic.P256()}
|
||||
|
||||
if fips140.Enabled() {
|
||||
defaultKexAlgos = slices.DeleteFunc(defaultKexAlgos, func(algo string) bool {
|
||||
_, ok := kexAlgoMap[algo]
|
||||
return !ok
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
p, _ := new(big.Int).SetString(oakleyGroup2, 16)
|
||||
kexAlgoMap[InsecureKeyExchangeDH1SHA1] = &dhGroup{
|
||||
g: new(big.Int).SetInt64(2),
|
||||
@@ -432,9 +452,6 @@ func init() {
|
||||
hashFunc: crypto.SHA512,
|
||||
}
|
||||
|
||||
kexAlgoMap[KeyExchangeECDHP521] = &ecdh{elliptic.P521()}
|
||||
kexAlgoMap[KeyExchangeECDHP384] = &ecdh{elliptic.P384()}
|
||||
kexAlgoMap[KeyExchangeECDHP256] = &ecdh{elliptic.P256()}
|
||||
kexAlgoMap[KeyExchangeCurve25519] = &curve25519sha256{}
|
||||
kexAlgoMap[keyExchangeCurve25519LibSSH] = &curve25519sha256{}
|
||||
kexAlgoMap[InsecureKeyExchangeDHGEXSHA1] = &dhGEXSHA{hashFunc: crypto.SHA1}
|
||||
@@ -454,15 +471,17 @@ func (kp *curve25519KeyPair) generate(rand io.Reader) error {
|
||||
if _, err := io.ReadFull(rand, kp.priv[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
curve25519.ScalarBaseMult(&kp.pub, &kp.priv)
|
||||
p, err := curve25519.X25519(kp.priv[:], curve25519.Basepoint)
|
||||
if err != nil {
|
||||
return fmt.Errorf("curve25519: %w", err)
|
||||
}
|
||||
if len(p) != 32 {
|
||||
return fmt.Errorf("curve25519: internal error: X25519 returned %d bytes, expected 32", len(p))
|
||||
}
|
||||
copy(kp.pub[:], p)
|
||||
return nil
|
||||
}
|
||||
|
||||
// curve25519Zeros is just an array of 32 zero bytes so that we have something
|
||||
// convenient to compare against in order to reject curve25519 points with the
|
||||
// wrong order.
|
||||
var curve25519Zeros [32]byte
|
||||
|
||||
func (kex *curve25519sha256) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) {
|
||||
var kp curve25519KeyPair
|
||||
if err := kp.generate(rand); err != nil {
|
||||
@@ -485,11 +504,9 @@ func (kex *curve25519sha256) Client(c packetConn, rand io.Reader, magics *handsh
|
||||
return nil, errors.New("ssh: peer's curve25519 public value has wrong length")
|
||||
}
|
||||
|
||||
var servPub, secret [32]byte
|
||||
copy(servPub[:], reply.EphemeralPubKey)
|
||||
curve25519.ScalarMult(&secret, &kp.priv, &servPub)
|
||||
if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 {
|
||||
return nil, errors.New("ssh: peer's curve25519 public value has wrong order")
|
||||
secret, err := curve25519.X25519(kp.priv[:], reply.EphemeralPubKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ssh: peer's curve25519 public value is not valid: %w", err)
|
||||
}
|
||||
|
||||
h := crypto.SHA256.New()
|
||||
@@ -531,11 +548,9 @@ func (kex *curve25519sha256) Server(c packetConn, rand io.Reader, magics *handsh
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var clientPub, secret [32]byte
|
||||
copy(clientPub[:], kexInit.ClientPubKey)
|
||||
curve25519.ScalarMult(&secret, &kp.priv, &clientPub)
|
||||
if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 {
|
||||
return nil, errors.New("ssh: peer's curve25519 public value has wrong order")
|
||||
secret, err := curve25519.X25519(kp.priv[:], kexInit.ClientPubKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ssh: peer's curve25519 public value is not valid: %w", err)
|
||||
}
|
||||
|
||||
hostKeyBytes := priv.PublicKey().Marshal()
|
||||
@@ -704,15 +719,9 @@ func (gex *dhGEXSHA) Server(c packetConn, randSource io.Reader, magics *handshak
|
||||
kexDHGexRequest.MaxBits, kexDHGexRequest.PreferredBits)
|
||||
}
|
||||
|
||||
var p *big.Int
|
||||
// We hardcode sending Oakley Group 14 (2048 bits), Oakley Group 15 (3072
|
||||
// bits) or Oakley Group 16 (4096 bits), based on the requested max size.
|
||||
if kexDHGexRequest.MaxBits < 3072 {
|
||||
p, _ = new(big.Int).SetString(oakleyGroup14, 16)
|
||||
} else if kexDHGexRequest.MaxBits < 4096 {
|
||||
p, _ = new(big.Int).SetString(oakleyGroup15, 16)
|
||||
} else {
|
||||
p, _ = new(big.Int).SetString(oakleyGroup16, 16)
|
||||
p, err := chooseDH(kexDHGexRequest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
g := big.NewInt(2)
|
||||
@@ -791,3 +800,65 @@ func (gex *dhGEXSHA) Server(c packetConn, randSource io.Reader, magics *handshak
|
||||
Hash: gex.hashFunc,
|
||||
}, err
|
||||
}
|
||||
|
||||
type dhKEXGroup struct {
|
||||
size int
|
||||
p *big.Int
|
||||
}
|
||||
|
||||
// supportedDHKEXGroups returns the DH groups the server is willing to offer
|
||||
// for diffie-hellman-group-exchange-* key exchanges. The list is built lazily
|
||||
// on first use to keep the hex-to-big.Int parse out of package initialization.
|
||||
var supportedDHKEXGroups = sync.OnceValue(func() []dhKEXGroup {
|
||||
specs := []struct {
|
||||
size int
|
||||
hex string
|
||||
}{
|
||||
{2048, oakleyGroup14},
|
||||
{3072, oakleyGroup15},
|
||||
{4096, oakleyGroup16},
|
||||
}
|
||||
out := make([]dhKEXGroup, 0, len(specs))
|
||||
for _, s := range specs {
|
||||
p, _ := new(big.Int).SetString(s.hex, 16)
|
||||
out = append(out, dhKEXGroup{size: s.size, p: p})
|
||||
}
|
||||
return out
|
||||
})
|
||||
|
||||
// chooseDH picks a DH group for the given client request, mirroring the
|
||||
// algorithm used by OpenSSH's choose_dh in dh.c: prefer the smallest known
|
||||
// group larger than or equal to the client's PreferredBits, and otherwise pick
|
||||
// the largest group within the accepted [MinBits, MaxBits] range.
|
||||
func chooseDH(req kexDHGexRequestMsg) (*big.Int, error) {
|
||||
var best *big.Int
|
||||
bestSize := 0
|
||||
wantBits := int(req.PreferredBits)
|
||||
|
||||
for _, group := range supportedDHKEXGroups() {
|
||||
if uint32(group.size) < req.MinBits || uint32(group.size) > req.MaxBits {
|
||||
continue
|
||||
}
|
||||
|
||||
if bestSize == 0 {
|
||||
best = group.p
|
||||
bestSize = group.size
|
||||
continue
|
||||
}
|
||||
|
||||
closerFromAbove := group.size >= wantBits && group.size < bestSize
|
||||
closerFromBelow := group.size > bestSize && bestSize < wantBits
|
||||
|
||||
if closerFromAbove || closerFromBelow {
|
||||
best = group.p
|
||||
bestSize = group.size
|
||||
}
|
||||
}
|
||||
|
||||
if bestSize == 0 {
|
||||
return nil, fmt.Errorf("ssh: no suitable DH group found for request min: %d, preferred: %d, max: %d",
|
||||
req.MinBits, req.PreferredBits, req.MaxBits)
|
||||
}
|
||||
|
||||
return best, nil
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ package ssh
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -65,6 +66,88 @@ func TestKexes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestChooseDH(t *testing.T) {
|
||||
oakley := map[int]string{
|
||||
2048: oakleyGroup14,
|
||||
3072: oakleyGroup15,
|
||||
4096: oakleyGroup16,
|
||||
}
|
||||
expected := func(size int) *big.Int {
|
||||
hex, ok := oakley[size]
|
||||
if !ok {
|
||||
t.Fatalf("test setup: no Oakley group for size %d", size)
|
||||
}
|
||||
p, _ := new(big.Int).SetString(hex, 16)
|
||||
return p
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
request kexDHGexRequestMsg
|
||||
want int // expected bit size; 0 means error expected
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "Standard 2048 request",
|
||||
request: kexDHGexRequestMsg{MinBits: 1024, PreferredBits: 2048, MaxBits: 8192},
|
||||
want: 2048,
|
||||
},
|
||||
{
|
||||
name: "Standard 3072 request",
|
||||
request: kexDHGexRequestMsg{MinBits: 1024, PreferredBits: 3072, MaxBits: 8192},
|
||||
want: 3072,
|
||||
},
|
||||
{
|
||||
name: "Standard 4096 request",
|
||||
request: kexDHGexRequestMsg{MinBits: 1024, PreferredBits: 4096, MaxBits: 8192},
|
||||
want: 4096,
|
||||
},
|
||||
{
|
||||
name: "Preferred 2500 -> Expect 3072 (round up)",
|
||||
request: kexDHGexRequestMsg{MinBits: 1024, PreferredBits: 2500, MaxBits: 8192},
|
||||
want: 3072,
|
||||
},
|
||||
{
|
||||
name: "Preferred 3500 -> Expect 4096 (round up)",
|
||||
request: kexDHGexRequestMsg{MinBits: 1024, PreferredBits: 3500, MaxBits: 8192},
|
||||
want: 4096,
|
||||
},
|
||||
{
|
||||
name: "Preferred too high (8000) -> Expect 4096 (cap at max available)",
|
||||
request: kexDHGexRequestMsg{MinBits: 1024, PreferredBits: 8000, MaxBits: 8192},
|
||||
want: 4096,
|
||||
},
|
||||
{
|
||||
name: "No group in range",
|
||||
request: kexDHGexRequestMsg{MinBits: 2500, PreferredBits: 2500, MaxBits: 2900},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := chooseDH(tt.request)
|
||||
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("chooseDH() error = %v, wantErr %t", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
if tt.wantErr {
|
||||
return
|
||||
}
|
||||
if got == nil {
|
||||
t.Fatalf("chooseDH() returned nil big.Int but expected success")
|
||||
}
|
||||
if got.BitLen() != tt.want {
|
||||
t.Errorf("chooseDH() got size = %d, want %d", got.BitLen(), tt.want)
|
||||
}
|
||||
if want := expected(tt.want); got.Cmp(want) != 0 {
|
||||
t.Errorf("chooseDH() returned the wrong group for size %d", tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkKexes(b *testing.B) {
|
||||
type kexResultErr struct {
|
||||
result *kexResult
|
||||
|
||||
+151
-18
@@ -27,6 +27,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/ssh/internal/bcrypt_pbkdf"
|
||||
@@ -75,7 +76,7 @@ func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, err err
|
||||
case InsecureKeyAlgoDSA:
|
||||
return parseDSA(in)
|
||||
case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
|
||||
return parseECDSA(in)
|
||||
return parseECDSA(in, algo)
|
||||
case KeyAlgoSKECDSA256:
|
||||
return parseSKECDSA(in)
|
||||
case KeyAlgoED25519:
|
||||
@@ -89,6 +90,11 @@ func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, err err
|
||||
}
|
||||
return cert, nil, nil
|
||||
}
|
||||
if keyFormat := keyFormatForAlgorithm(algo); keyFormat != "" {
|
||||
return nil, nil, fmt.Errorf("ssh: signature algorithm %q isn't a key format; key is malformed and should be re-encoded with type %q",
|
||||
algo, keyFormat)
|
||||
}
|
||||
|
||||
return nil, nil, fmt.Errorf("ssh: unknown key algorithm: %v", algo)
|
||||
}
|
||||
|
||||
@@ -191,9 +197,10 @@ func ParseKnownHosts(in []byte) (marker string, hosts []string, pubKey PublicKey
|
||||
return "", nil, nil, "", nil, io.EOF
|
||||
}
|
||||
|
||||
// ParseAuthorizedKey parses a public key from an authorized_keys
|
||||
// file used in OpenSSH according to the sshd(8) manual page.
|
||||
// ParseAuthorizedKey parses a public key from an authorized_keys file used in
|
||||
// OpenSSH according to the sshd(8) manual page. Invalid lines are ignored.
|
||||
func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, err error) {
|
||||
var lastErr error
|
||||
for len(in) > 0 {
|
||||
end := bytes.IndexByte(in, '\n')
|
||||
if end != -1 {
|
||||
@@ -222,6 +229,8 @@ func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []str
|
||||
|
||||
if out, comment, err = parseAuthorizedKey(in[i:]); err == nil {
|
||||
return out, comment, options, rest, nil
|
||||
} else {
|
||||
lastErr = err
|
||||
}
|
||||
|
||||
// No key type recognised. Maybe there's an options field at
|
||||
@@ -264,12 +273,18 @@ func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []str
|
||||
if out, comment, err = parseAuthorizedKey(in[i:]); err == nil {
|
||||
options = candidateOptions
|
||||
return out, comment, options, rest, nil
|
||||
} else {
|
||||
lastErr = err
|
||||
}
|
||||
|
||||
in = rest
|
||||
continue
|
||||
}
|
||||
|
||||
if lastErr != nil {
|
||||
return nil, "", nil, nil, fmt.Errorf("ssh: no key found; last parsing error for ignored line: %w", lastErr)
|
||||
}
|
||||
|
||||
return nil, "", nil, nil, errors.New("ssh: no key found")
|
||||
}
|
||||
|
||||
@@ -395,11 +410,11 @@ func NewSignerWithAlgorithms(signer AlgorithmSigner, algorithms []string) (Multi
|
||||
}
|
||||
|
||||
for _, algo := range algorithms {
|
||||
if !contains(supportedAlgos, algo) {
|
||||
if !slices.Contains(supportedAlgos, algo) {
|
||||
return nil, fmt.Errorf("ssh: algorithm %q is not supported for key type %q",
|
||||
algo, signer.PublicKey().Type())
|
||||
}
|
||||
if !contains(signerAlgos, algo) {
|
||||
if !slices.Contains(signerAlgos, algo) {
|
||||
return nil, fmt.Errorf("ssh: algorithm %q is restricted for the provided signer", algo)
|
||||
}
|
||||
}
|
||||
@@ -454,6 +469,12 @@ func parseRSA(in []byte) (out PublicKey, rest []byte, err error) {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// 8192 bits is also the maximum RSA key size accepted by crypto/tls for
|
||||
// signature verification:
|
||||
// https://github.com/golang/go/blob/69801b25/src/crypto/tls/handshake_client.go#L1096
|
||||
if w.N.BitLen() > 8192 {
|
||||
return nil, nil, errors.New("ssh: rsa modulus too large")
|
||||
}
|
||||
if w.E.BitLen() > 24 {
|
||||
return nil, nil, errors.New("ssh: exponent too large")
|
||||
}
|
||||
@@ -486,10 +507,13 @@ func (r *rsaPublicKey) Marshal() []byte {
|
||||
|
||||
func (r *rsaPublicKey) Verify(data []byte, sig *Signature) error {
|
||||
supportedAlgos := algorithmsForKeyFormat(r.Type())
|
||||
if !contains(supportedAlgos, sig.Format) {
|
||||
if !slices.Contains(supportedAlgos, sig.Format) {
|
||||
return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, r.Type())
|
||||
}
|
||||
hash := hashFuncs[sig.Format]
|
||||
hash, err := hashFunc(sig.Format)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h := hash.New()
|
||||
h.Write(data)
|
||||
digest := h.Sum(nil)
|
||||
@@ -556,6 +580,24 @@ func checkDSAParams(param *dsa.Parameters) error {
|
||||
return fmt.Errorf("ssh: unsupported DSA key size %d", l)
|
||||
}
|
||||
|
||||
// FIPS 186-2 specifies that Q must be exactly 160 bits. We must enforce
|
||||
// this to prevent DoS attacks where an attacker sends a huge Q which makes
|
||||
// verification slow.
|
||||
if l := param.Q.BitLen(); l != 160 {
|
||||
return fmt.Errorf("ssh: unsupported DSA sub-prime size %d", l)
|
||||
}
|
||||
|
||||
// The generator G is an element of the group, so it must be strictly less
|
||||
// than the modulus P.
|
||||
if param.G.Cmp(param.P) >= 0 {
|
||||
return errors.New("ssh: DSA generator larger than modulus")
|
||||
}
|
||||
|
||||
// G must be positive.
|
||||
if param.G.Sign() <= 0 {
|
||||
return errors.New("ssh: DSA generator must be positive")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -578,6 +620,14 @@ func parseDSA(in []byte) (out PublicKey, rest []byte, err error) {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// The public value Y must be a non-zero element of the group, i.e.
|
||||
// strictly between 0 and P. crypto/dsa.Verify does not range-check Y,
|
||||
// so we reject out-of-range values here to prevent a maliciously
|
||||
// oversized Y from slowing verification.
|
||||
if w.Y.Sign() <= 0 || w.Y.Cmp(w.P) >= 0 {
|
||||
return nil, nil, errors.New("ssh: DSA public value Y out of range")
|
||||
}
|
||||
|
||||
key := &dsaPublicKey{
|
||||
Parameters: param,
|
||||
Y: w.Y,
|
||||
@@ -606,7 +656,11 @@ func (k *dsaPublicKey) Verify(data []byte, sig *Signature) error {
|
||||
if sig.Format != k.Type() {
|
||||
return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
|
||||
}
|
||||
h := hashFuncs[sig.Format].New()
|
||||
hash, err := hashFunc(sig.Format)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h := hash.New()
|
||||
h.Write(data)
|
||||
digest := h.Sum(nil)
|
||||
|
||||
@@ -651,7 +705,11 @@ func (k *dsaPrivateKey) SignWithAlgorithm(rand io.Reader, data []byte, algorithm
|
||||
return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm)
|
||||
}
|
||||
|
||||
h := hashFuncs[k.PublicKey().Type()].New()
|
||||
hash, err := hashFunc(k.PublicKey().Type())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h := hash.New()
|
||||
h.Write(data)
|
||||
digest := h.Sum(nil)
|
||||
r, s, err := dsa.Sign(rand, k.PrivateKey, digest)
|
||||
@@ -748,7 +806,7 @@ func supportedEllipticCurve(curve elliptic.Curve) bool {
|
||||
}
|
||||
|
||||
// parseECDSA parses an ECDSA key according to RFC 5656, section 3.1.
|
||||
func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) {
|
||||
func parseECDSA(in []byte, expectedType string) (out PublicKey, rest []byte, err error) {
|
||||
var w struct {
|
||||
Curve string
|
||||
KeyBytes []byte
|
||||
@@ -759,6 +817,12 @@ func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
actualType := "ecdsa-sha2-" + w.Curve
|
||||
if expectedType != actualType {
|
||||
return nil, nil, fmt.Errorf("ssh: algorithm type mismatch: expected %q, found curve %q (type %q)",
|
||||
expectedType, w.Curve, actualType)
|
||||
}
|
||||
|
||||
key := new(ecdsa.PublicKey)
|
||||
|
||||
switch w.Curve {
|
||||
@@ -801,8 +865,11 @@ func (k *ecdsaPublicKey) Verify(data []byte, sig *Signature) error {
|
||||
if sig.Format != k.Type() {
|
||||
return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
|
||||
}
|
||||
|
||||
h := hashFuncs[sig.Format].New()
|
||||
hash, err := hashFunc(sig.Format)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h := hash.New()
|
||||
h.Write(data)
|
||||
digest := h.Sum(nil)
|
||||
|
||||
@@ -840,11 +907,25 @@ type skFields struct {
|
||||
Counter uint32
|
||||
}
|
||||
|
||||
// flagUserPresence is the "user present" bit (UP) in the SK signature
|
||||
// flags, matching the FIDO CTAP2 authenticatorData UP flag. See
|
||||
// openssh/PROTOCOL.u2f.
|
||||
const flagUserPresence = 0x01
|
||||
|
||||
// errSKMissingUserPresence is returned by SK key Verify methods when
|
||||
// the signature does not assert user presence and the key was not
|
||||
// marked as no-touch-required.
|
||||
var errSKMissingUserPresence = errors.New("ssh: signature missing required user presence flag")
|
||||
|
||||
type skECDSAPublicKey struct {
|
||||
// application is a URL-like string, typically "ssh:" for SSH.
|
||||
// see openssh/PROTOCOL.u2f for details.
|
||||
application string
|
||||
ecdsa.PublicKey
|
||||
// noTouchRequired, when true, disables the default user-presence
|
||||
// check in Verify. It is set by skKeyWithoutUP on a clone of the
|
||||
// key, never on an instance shared across authentication attempts.
|
||||
noTouchRequired bool
|
||||
}
|
||||
|
||||
func (k *skECDSAPublicKey) Type() string {
|
||||
@@ -905,8 +986,11 @@ func (k *skECDSAPublicKey) Verify(data []byte, sig *Signature) error {
|
||||
if sig.Format != k.Type() {
|
||||
return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
|
||||
}
|
||||
|
||||
h := hashFuncs[sig.Format].New()
|
||||
hash, err := hashFunc(sig.Format)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h := hash.New()
|
||||
h.Write([]byte(k.application))
|
||||
appDigest := h.Sum(nil)
|
||||
|
||||
@@ -927,6 +1011,10 @@ func (k *skECDSAPublicKey) Verify(data []byte, sig *Signature) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if skf.Flags&flagUserPresence == 0 && !k.noTouchRequired {
|
||||
return errSKMissingUserPresence
|
||||
}
|
||||
|
||||
blob := struct {
|
||||
ApplicationDigest []byte `ssh:"rest"`
|
||||
Flags byte
|
||||
@@ -960,6 +1048,10 @@ type skEd25519PublicKey struct {
|
||||
// see openssh/PROTOCOL.u2f for details.
|
||||
application string
|
||||
ed25519.PublicKey
|
||||
// noTouchRequired, when true, disables the default user-presence
|
||||
// check in Verify. It is set by skKeyWithoutUP on a clone of the
|
||||
// key, never on an instance shared across authentication attempts.
|
||||
noTouchRequired bool
|
||||
}
|
||||
|
||||
func (k *skEd25519PublicKey) Type() string {
|
||||
@@ -1009,7 +1101,11 @@ func (k *skEd25519PublicKey) Verify(data []byte, sig *Signature) error {
|
||||
return fmt.Errorf("invalid size %d for Ed25519 public key", l)
|
||||
}
|
||||
|
||||
h := hashFuncs[sig.Format].New()
|
||||
hash, err := hashFunc(sig.Format)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h := hash.New()
|
||||
h.Write([]byte(k.application))
|
||||
appDigest := h.Sum(nil)
|
||||
|
||||
@@ -1030,6 +1126,10 @@ func (k *skEd25519PublicKey) Verify(data []byte, sig *Signature) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if skf.Flags&flagUserPresence == 0 && !k.noTouchRequired {
|
||||
return errSKMissingUserPresence
|
||||
}
|
||||
|
||||
blob := struct {
|
||||
ApplicationDigest []byte `ssh:"rest"`
|
||||
Flags byte
|
||||
@@ -1112,11 +1212,14 @@ func (s *wrappedSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm
|
||||
algorithm = s.pubKey.Type()
|
||||
}
|
||||
|
||||
if !contains(s.Algorithms(), algorithm) {
|
||||
if !slices.Contains(s.Algorithms(), algorithm) {
|
||||
return nil, fmt.Errorf("ssh: unsupported signature algorithm %q for key format %q", algorithm, s.pubKey.Type())
|
||||
}
|
||||
|
||||
hashFunc := hashFuncs[algorithm]
|
||||
hashFunc, err := hashFunc(algorithm)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var digest []byte
|
||||
if hashFunc != 0 {
|
||||
h := hashFunc.New()
|
||||
@@ -1369,6 +1472,17 @@ func passphraseProtectedOpenSSHKey(passphrase []byte) openSSHDecryptFunc {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// OpenSSH does not impose an upper bound on the bcrypt round count
|
||||
// stored in the key file, but bcrypt_pbkdf cost is linear in rounds:
|
||||
// the default is 16, ssh-keygen lets users pick anything up to
|
||||
// INT_MAX. Cap at 2048 (128x the default, a few seconds of CPU) so
|
||||
// that an oversized value in the file cannot tie up the caller for
|
||||
// months.
|
||||
const maxRounds = 1 << 11
|
||||
if opts.Rounds > maxRounds {
|
||||
return nil, fmt.Errorf("ssh: bcrypt KDF rounds %d exceed maximum %d", opts.Rounds, maxRounds)
|
||||
}
|
||||
|
||||
k, err := bcrypt_pbkdf.Key(passphrase, []byte(opts.Salt), int(opts.Rounds), 32+16)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -1451,6 +1565,7 @@ type openSSHEncryptedPrivateKey struct {
|
||||
NumKeys uint32
|
||||
PubKey []byte
|
||||
PrivKeyBlock []byte
|
||||
Rest []byte `ssh:"rest"`
|
||||
}
|
||||
|
||||
type openSSHPrivateKey struct {
|
||||
@@ -1537,10 +1652,28 @@ func parseOpenSSHPrivateKey(key []byte, decrypt openSSHDecryptFunc) (crypto.Priv
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Mirror the validation done in parseRSA for public keys: cap the
|
||||
// modulus at the same limit enforced by crypto/tls, reject oversized
|
||||
// or invalid exponents, and additionally bound the prime factors to
|
||||
// avoid the expensive CRT coefficient recomputation in pk.Precompute.
|
||||
if key.N.BitLen() > 8192 {
|
||||
return nil, errors.New("ssh: rsa modulus too large")
|
||||
}
|
||||
if key.P.BitLen() > 4096 || key.Q.BitLen() > 4096 {
|
||||
return nil, errors.New("ssh: rsa prime too large")
|
||||
}
|
||||
if key.E.BitLen() > 24 {
|
||||
return nil, errors.New("ssh: exponent too large")
|
||||
}
|
||||
e := key.E.Int64()
|
||||
if e < 3 || e&1 == 0 {
|
||||
return nil, errors.New("ssh: incorrect exponent")
|
||||
}
|
||||
|
||||
pk := &rsa.PrivateKey{
|
||||
PublicKey: rsa.PublicKey{
|
||||
N: key.N,
|
||||
E: int(key.E.Int64()),
|
||||
E: int(e),
|
||||
},
|
||||
D: key.D,
|
||||
Primes: []*big.Int{key.P, key.Q},
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
@@ -19,6 +20,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -59,6 +61,17 @@ func TestKeyMarshalParse(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePublicKeyWithSigningAlgoAsKeyFormat(t *testing.T) {
|
||||
key := []byte(`rsa-sha2-256 AAAADHJzYS1zaGEyLTI1NgAAAAMBAAEAAAEBAJ7qMyjLXEJCCJmRknuCLo0uPi5GrPY5pQYr84lhlN8Gor5KVL2LKYCW4e70r5xzj7SrHHSCft1FMlYg1KDO9xrprJh733kQqAPWETmSuH0EfRtGtcH6EarKyVxk6As076/yNiiMKVBtG0RPa1L7FviTfcYK4vnCCVrbv3RmA5CCzuG5BSMbRLxzVb4Ri3p8jhxYT8N4QGe/2yqvJLys5vQ9szpZR3tcFp3DJIVZhBRfR6LnoY23XZniAAMQaUVBX86dXQ++dNwAwZSXSt9Og+AniOCiBYqhNVa5n3DID/H7YtEtG+CbZr3r2KD3fv8AfSLRar4XOp8rsRdD31h/kr8=`)
|
||||
_, _, _, _, err := ParseAuthorizedKey(key)
|
||||
if err == nil {
|
||||
t.Fatal("parsing a public key using a signature algorithm as the key format succeeded unexpectedly")
|
||||
}
|
||||
if !strings.Contains(err.Error(), `signature algorithm "rsa-sha2-256" isn't a key format`) {
|
||||
t.Errorf(`got %v, expected 'signature algorithm "rsa-sha2-256" isn't a key format'`, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsupportedCurves(t *testing.T) {
|
||||
raw, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
|
||||
if err != nil {
|
||||
@@ -205,6 +218,214 @@ func TestParseRSAPrivateKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRSAModulusTooLarge(t *testing.T) {
|
||||
rsa16384 := "ssh-rsa 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"
|
||||
_, _, _, _, err := ParseAuthorizedKey([]byte(rsa16384))
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("ParseAuthorizedKey accepted a 16384-bit modulus; expected it to be rejected")
|
||||
}
|
||||
|
||||
expectedError := "rsa modulus too large"
|
||||
if !strings.Contains(err.Error(), expectedError) {
|
||||
t.Errorf("unexpected error message: got %q, want substring %q", err.Error(), expectedError)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePrivateKeyRSAModulusTooLarge(t *testing.T) {
|
||||
rsa16384 := []byte(`-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
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
|
||||
QHAxNnM=
|
||||
-----END OPENSSH PRIVATE KEY-----
|
||||
`)
|
||||
_, err := ParseRawPrivateKey(rsa16384)
|
||||
if err == nil {
|
||||
t.Fatal("ParseRawPrivateKey accepted a 16384-bit modulus; expected it to be rejected")
|
||||
}
|
||||
|
||||
expectedError := "rsa modulus too large"
|
||||
if !strings.Contains(err.Error(), expectedError) {
|
||||
t.Errorf("unexpected error message: got %q, want substring %q", err.Error(), expectedError)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseECPrivateKey(t *testing.T) {
|
||||
key := testPrivateKeys["ecdsa"]
|
||||
|
||||
@@ -260,6 +481,21 @@ func TestParseEncryptedPrivateKeysWithPassphrase(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseEncryptedPrivateKeysWithUnsupportedCiphers(t *testing.T) {
|
||||
for _, tt := range testdata.UnsupportedCipherData {
|
||||
t.Run(tt.Name, func(t *testing.T) {
|
||||
_, err := ParsePrivateKeyWithPassphrase(tt.PEMBytes, []byte(tt.EncryptionKey))
|
||||
if err == nil {
|
||||
t.Fatalf("expected 'unknown cipher' error for %q, got nil", tt.Name)
|
||||
// If this cipher is now supported, remove it from testdata.UnsupportedCipherData
|
||||
}
|
||||
if !strings.Contains(err.Error(), "unknown cipher") {
|
||||
t.Errorf("wanted 'unknown cipher' error, got %v", err.Error())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseEncryptedPrivateKeysWithIncorrectPassphrase(t *testing.T) {
|
||||
pem := testdata.PEMEncryptedKeys[0].PEMBytes
|
||||
for i := 0; i < 4096; i++ {
|
||||
@@ -270,6 +506,38 @@ func TestParseEncryptedPrivateKeysWithIncorrectPassphrase(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseEncryptedPrivateKeyExcessiveBcryptRounds(t *testing.T) {
|
||||
// Craft a minimal openssh-key-v1 blob whose KdfOpts declares a bcrypt
|
||||
// round count above the accepted maximum. The check must reject the file
|
||||
// before bcrypt_pbkdf is invoked, so the rest of the blob (public key,
|
||||
// encrypted body) can be empty.
|
||||
kdfOpts := Marshal(struct {
|
||||
Salt []byte
|
||||
Rounds uint32
|
||||
}{
|
||||
Salt: []byte("salt-not-used"),
|
||||
Rounds: (1 << 11) + 1,
|
||||
})
|
||||
header := Marshal(openSSHEncryptedPrivateKey{
|
||||
CipherName: "aes256-ctr",
|
||||
KdfName: "bcrypt",
|
||||
KdfOpts: string(kdfOpts),
|
||||
NumKeys: 1,
|
||||
})
|
||||
pemBytes := pem.EncodeToMemory(&pem.Block{
|
||||
Type: "OPENSSH PRIVATE KEY",
|
||||
Bytes: append([]byte(privateKeyAuthMagic), header...),
|
||||
})
|
||||
|
||||
_, err := ParseRawPrivateKeyWithPassphrase(pemBytes, []byte("password"))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for excessive bcrypt rounds, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "bcrypt KDF rounds") {
|
||||
t.Errorf("got error %q, want substring %q", err.Error(), "bcrypt KDF rounds")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDSA(t *testing.T) {
|
||||
// We actually exercise the ParsePrivateKey codepath here, as opposed to
|
||||
// using the ParseRawPrivateKey+NewSignerFromKey path that testdata_test.go
|
||||
@@ -330,6 +598,72 @@ func TestMarshalParsePublicKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDSAHugeQ(t *testing.T) {
|
||||
P := new(big.Int).Lsh(big.NewInt(1), 1023)
|
||||
Q := new(big.Int).Lsh(big.NewInt(1), 20000) // very large
|
||||
// G and Y: Dummy values, just needs to be < P to pass that specific check
|
||||
G := big.NewInt(2)
|
||||
Y := big.NewInt(5)
|
||||
|
||||
rawKey := struct {
|
||||
P, Q, G, Y *big.Int
|
||||
}{
|
||||
P: P,
|
||||
Q: Q,
|
||||
G: G,
|
||||
Y: Y,
|
||||
}
|
||||
|
||||
inputBytes := Marshal(&rawKey)
|
||||
|
||||
_, _, err := parseDSA(inputBytes)
|
||||
if err == nil {
|
||||
t.Fatal("parseDSA accepted a DSA key with large Q")
|
||||
}
|
||||
|
||||
expectedError := "ssh: unsupported DSA sub-prime size"
|
||||
if !strings.Contains(err.Error(), expectedError) {
|
||||
t.Errorf("unexpected error message: got %q, want substring %q", err.Error(), expectedError)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDSAYOutOfRange(t *testing.T) {
|
||||
// Valid 1024/160 parameters (values don't need to be a real DSA group,
|
||||
// they only need to pass the checkDSAParams bit-length checks and the
|
||||
// G < P / G > 0 checks).
|
||||
P := new(big.Int).Lsh(big.NewInt(1), 1023)
|
||||
P.SetBit(P, 0, 1) // make P odd so it can pass as a prime candidate shape
|
||||
Q := new(big.Int).Lsh(big.NewInt(1), 159)
|
||||
Q.SetBit(Q, 0, 1)
|
||||
G := big.NewInt(2)
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
Y *big.Int
|
||||
}{
|
||||
{"Y_zero", big.NewInt(0)},
|
||||
{"Y_negative", big.NewInt(-1)},
|
||||
{"Y_equals_P", new(big.Int).Set(P)},
|
||||
{"Y_greater_than_P", new(big.Int).Add(P, big.NewInt(1))},
|
||||
{"Y_much_greater_than_P", new(big.Int).Lsh(big.NewInt(1), 20000)},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rawKey := struct {
|
||||
P, Q, G, Y *big.Int
|
||||
}{P: P, Q: Q, G: G, Y: tc.Y}
|
||||
|
||||
_, _, err := parseDSA(Marshal(&rawKey))
|
||||
if err == nil {
|
||||
t.Fatalf("parseDSA accepted a DSA key with Y=%s (P=%s)", tc.Y, P)
|
||||
}
|
||||
expectedError := "DSA public value Y out of range"
|
||||
if !strings.Contains(err.Error(), expectedError) {
|
||||
t.Errorf("unexpected error message: got %q, want substring %q", err.Error(), expectedError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarshalPrivateKey(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -734,6 +1068,296 @@ func TestSKKeys(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// skTestHarness builds SK-formatted signatures over a fixed payload
|
||||
// using a caller-supplied signing function, letting tests vary the UP
|
||||
// flag byte without duplicating the wire-format scaffolding.
|
||||
type skTestHarness struct {
|
||||
format string
|
||||
application string
|
||||
data []byte
|
||||
// sign takes the SHA-256 digest of the marshalled SK blob and
|
||||
// returns the value to embed in Signature.Blob. For ECDSA keys the
|
||||
// helper feeds the digest to ecdsa.Sign; for ed25519 the helper
|
||||
// feeds the raw marshalled blob to ed25519.Sign.
|
||||
signDigest func(digest []byte) []byte
|
||||
signBlob func(blob []byte) []byte
|
||||
}
|
||||
|
||||
func (h skTestHarness) sign(t *testing.T, flags byte) *Signature {
|
||||
t.Helper()
|
||||
hsh := sha256.New()
|
||||
hsh.Write([]byte(h.application))
|
||||
appDigest := hsh.Sum(nil)
|
||||
|
||||
hsh.Reset()
|
||||
hsh.Write(h.data)
|
||||
dataDigest := hsh.Sum(nil)
|
||||
|
||||
var counter uint32 = 1
|
||||
blob := struct {
|
||||
ApplicationDigest []byte `ssh:"rest"`
|
||||
Flags byte
|
||||
Counter uint32
|
||||
MessageDigest []byte `ssh:"rest"`
|
||||
}{appDigest, flags, counter, dataDigest}
|
||||
marshalled := Marshal(blob)
|
||||
|
||||
var sigBlob []byte
|
||||
if h.signDigest != nil {
|
||||
hsh.Reset()
|
||||
hsh.Write(marshalled)
|
||||
sigBlob = h.signDigest(hsh.Sum(nil))
|
||||
} else {
|
||||
sigBlob = h.signBlob(marshalled)
|
||||
}
|
||||
|
||||
return &Signature{
|
||||
Format: h.format,
|
||||
Blob: sigBlob,
|
||||
Rest: Marshal(struct {
|
||||
Flags byte
|
||||
Counter uint32
|
||||
}{flags, counter}),
|
||||
}
|
||||
}
|
||||
|
||||
func TestSKUserPresence(t *testing.T) {
|
||||
ecKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
h := skTestHarness{
|
||||
format: "sk-ecdsa-sha2-nistp256@openssh.com",
|
||||
application: "ssh:",
|
||||
data: []byte("test data"),
|
||||
signDigest: func(digest []byte) []byte {
|
||||
r, s, err := ecdsa.Sign(rand.Reader, ecKey, digest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return Marshal(struct{ R, S *big.Int }{r, s})
|
||||
},
|
||||
}
|
||||
|
||||
pk := &skECDSAPublicKey{
|
||||
application: h.application,
|
||||
PublicKey: ecKey.PublicKey,
|
||||
}
|
||||
|
||||
// Valid signature with UP=1 should pass.
|
||||
if err := pk.Verify(h.data, h.sign(t, flagUserPresence)); err != nil {
|
||||
t.Errorf("Verify failed with UP=1: %v", err)
|
||||
}
|
||||
|
||||
// Valid signature with UP=0 should fail with the user-presence sentinel.
|
||||
sigNoUP := h.sign(t, 0)
|
||||
if err := pk.Verify(h.data, sigNoUP); !errors.Is(err, errSKMissingUserPresence) {
|
||||
t.Errorf("expected errSKMissingUserPresence, got: %v", err)
|
||||
}
|
||||
|
||||
// UV set but UP clear must still fail: we only waive UP, never UV-only.
|
||||
if err := pk.Verify(h.data, h.sign(t, 0x04)); !errors.Is(err, errSKMissingUserPresence) {
|
||||
t.Errorf("UV-only (flags=0x04): expected errSKMissingUserPresence, got: %v", err)
|
||||
}
|
||||
|
||||
// With noTouchRequired, UP=0 passes; UP=1+UV=1 also passes.
|
||||
pk.noTouchRequired = true
|
||||
if err := pk.Verify(h.data, sigNoUP); err != nil {
|
||||
t.Errorf("Verify with noTouchRequired failed: %v", err)
|
||||
}
|
||||
if err := pk.Verify(h.data, h.sign(t, flagUserPresence|0x04)); err != nil {
|
||||
t.Errorf("Verify UP|UV with noTouchRequired failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSKKeyWithoutUP(t *testing.T) {
|
||||
ecKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
edPub, _, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
skEC := &skECDSAPublicKey{PublicKey: ecKey.PublicKey}
|
||||
skED := &skEd25519PublicKey{PublicKey: edPub}
|
||||
certEC := &Certificate{Key: &skECDSAPublicKey{PublicKey: ecKey.PublicKey}}
|
||||
certED := &Certificate{Key: &skEd25519PublicKey{PublicKey: edPub}}
|
||||
rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rsaPub, err := NewPublicKey(&rsaKey.PublicKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
certRSA := &Certificate{Key: rsaPub}
|
||||
|
||||
// SK raw keys: return a clone with the flag set, original untouched.
|
||||
gotEC := skKeyWithoutUP(skEC)
|
||||
if gotEC == skEC {
|
||||
t.Error("skECDSAPublicKey: expected a clone, got the original pointer")
|
||||
}
|
||||
if !gotEC.(*skECDSAPublicKey).noTouchRequired {
|
||||
t.Error("skECDSAPublicKey clone: noTouchRequired not set")
|
||||
}
|
||||
if skEC.noTouchRequired {
|
||||
t.Error("skECDSAPublicKey: original mutated")
|
||||
}
|
||||
|
||||
gotED := skKeyWithoutUP(skED)
|
||||
if gotED == skED {
|
||||
t.Error("skEd25519PublicKey: expected a clone, got the original pointer")
|
||||
}
|
||||
if !gotED.(*skEd25519PublicKey).noTouchRequired {
|
||||
t.Error("skEd25519PublicKey clone: noTouchRequired not set")
|
||||
}
|
||||
if skED.noTouchRequired {
|
||||
t.Error("skEd25519PublicKey: original mutated")
|
||||
}
|
||||
|
||||
// Certificate wrapping SK: return a clone of the cert with a cloned
|
||||
// SK key inside. Neither the original cert nor the original inner
|
||||
// key must be mutated.
|
||||
originalInnerEC := certEC.Key
|
||||
gotCertEC := skKeyWithoutUP(certEC)
|
||||
if gotCertEC == certEC {
|
||||
t.Error("*Certificate(SK ecdsa): expected a clone, got the original pointer")
|
||||
}
|
||||
if got := gotCertEC.(*Certificate).Key.(*skECDSAPublicKey); !got.noTouchRequired {
|
||||
t.Error("*Certificate(SK ecdsa): inner clone missing noTouchRequired")
|
||||
}
|
||||
if certEC.Key != originalInnerEC {
|
||||
t.Error("*Certificate(SK ecdsa): original cert's Key pointer mutated")
|
||||
}
|
||||
if originalInnerEC.(*skECDSAPublicKey).noTouchRequired {
|
||||
t.Error("*Certificate(SK ecdsa): original inner key mutated")
|
||||
}
|
||||
|
||||
gotCertED := skKeyWithoutUP(certED)
|
||||
if gotCertED == certED {
|
||||
t.Error("*Certificate(SK ed25519): expected a clone, got the original pointer")
|
||||
}
|
||||
if got := gotCertED.(*Certificate).Key.(*skEd25519PublicKey); !got.noTouchRequired {
|
||||
t.Error("*Certificate(SK ed25519): inner clone missing noTouchRequired")
|
||||
}
|
||||
|
||||
// Non-SK key inside a cert: return original unchanged (nothing to clone).
|
||||
if got := skKeyWithoutUP(certRSA); got != certRSA {
|
||||
t.Error("*Certificate(RSA): expected the original pointer back")
|
||||
}
|
||||
|
||||
// Plain non-SK key: return original unchanged.
|
||||
if got := skKeyWithoutUP(rsaPub); got != rsaPub {
|
||||
t.Error("rsaPublicKey: expected the original pointer back")
|
||||
}
|
||||
|
||||
// Pathological: *Certificate whose Key is itself a *Certificate.
|
||||
// The SSH cert format forbids this and parseCert rejects it, but
|
||||
// a Go caller can still construct such a value. skKeyWithoutUP
|
||||
// must not recurse into it (or panic); it returns the input
|
||||
// unchanged. This also defends against a hypothetical cycle built
|
||||
// from hand-constructed Certificate pointers.
|
||||
nestedCert := &Certificate{Key: &Certificate{Key: skEC}}
|
||||
if got := skKeyWithoutUP(nestedCert); got != nestedCert {
|
||||
t.Error("*Certificate wrapping *Certificate: expected the original pointer back")
|
||||
}
|
||||
selfCycle := &Certificate{}
|
||||
selfCycle.Key = selfCycle
|
||||
if got := skKeyWithoutUP(selfCycle); got != selfCycle {
|
||||
t.Error("self-referential *Certificate: expected the original pointer back")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoTouchAllowed(t *testing.T) {
|
||||
ecKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sk := &skECDSAPublicKey{PublicKey: ecKey.PublicKey}
|
||||
certNoExt := &Certificate{Key: sk}
|
||||
certOptOut := &Certificate{
|
||||
Key: sk,
|
||||
Permissions: Permissions{Extensions: map[string]string{"no-touch-required": ""}},
|
||||
}
|
||||
// Non-empty value: OpenSSH writes "" but any value must be accepted
|
||||
// because the check is presence-only.
|
||||
certOptOutNonEmpty := &Certificate{
|
||||
Key: sk,
|
||||
Permissions: Permissions{Extensions: map[string]string{"no-touch-required": "yes"}},
|
||||
}
|
||||
// no-touch-required belongs in Extensions, never CriticalOptions.
|
||||
// Putting it in CriticalOptions must NOT be treated as opt-out.
|
||||
certCritOnly := &Certificate{
|
||||
Key: sk,
|
||||
Permissions: Permissions{CriticalOptions: map[string]string{"no-touch-required": ""}},
|
||||
}
|
||||
|
||||
permsEmpty := &Permissions{}
|
||||
permsOptOut := &Permissions{Extensions: map[string]string{"no-touch-required": ""}}
|
||||
permsCritOnly := &Permissions{CriticalOptions: map[string]string{"no-touch-required": ""}}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
pub PublicKey
|
||||
perms *Permissions
|
||||
want bool
|
||||
}{
|
||||
{"nil perms, no cert", sk, nil, false},
|
||||
{"empty perms, no cert", sk, permsEmpty, false},
|
||||
{"perms opt-out, raw key", sk, permsOptOut, true},
|
||||
{"nil perms, cert opt-out", certOptOut, nil, true},
|
||||
{"nil perms, cert opt-out non-empty value", certOptOutNonEmpty, nil, true},
|
||||
{"nil perms, cert no ext", certNoExt, nil, false},
|
||||
{"perms opt-out, cert no ext", certNoExt, permsOptOut, true},
|
||||
{"empty perms, cert opt-out", certOptOut, permsEmpty, true},
|
||||
// Negative controls: CriticalOptions must not waive UP.
|
||||
{"critical-options only, raw key", sk, permsCritOnly, false},
|
||||
{"critical-options only, cert", certCritOnly, nil, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := noTouchAllowed(tc.pub, tc.perms); got != tc.want {
|
||||
t.Errorf("noTouchAllowed = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSKUserPresenceEd25519(t *testing.T) {
|
||||
pub, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := skTestHarness{
|
||||
format: "sk-ssh-ed25519@openssh.com",
|
||||
application: "ssh:",
|
||||
data: []byte("test data"),
|
||||
signBlob: func(blob []byte) []byte {
|
||||
return ed25519.Sign(priv, blob)
|
||||
},
|
||||
}
|
||||
|
||||
pk := &skEd25519PublicKey{
|
||||
application: h.application,
|
||||
PublicKey: pub,
|
||||
}
|
||||
|
||||
if err := pk.Verify(h.data, h.sign(t, flagUserPresence)); err != nil {
|
||||
t.Errorf("Verify failed with UP=1: %v", err)
|
||||
}
|
||||
sigNoUP := h.sign(t, 0)
|
||||
if err := pk.Verify(h.data, sigNoUP); !errors.Is(err, errSKMissingUserPresence) {
|
||||
t.Errorf("expected errSKMissingUserPresence, got: %v", err)
|
||||
}
|
||||
pk.noTouchRequired = true
|
||||
if err := pk.Verify(h.data, sigNoUP); err != nil {
|
||||
t.Errorf("Verify with noTouchRequired failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSignerWithAlgos(t *testing.T) {
|
||||
algorithSigner, ok := testSigners["rsa"].(AlgorithmSigner)
|
||||
if !ok {
|
||||
@@ -837,3 +1461,39 @@ cLYUOHfQDw==
|
||||
t.Fatal("parsing an SSH certificate using another certificate as signature key succeeded; expected failure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseECDSAAlgorithmMismatch(t *testing.T) {
|
||||
cases := []struct {
|
||||
keyName string // key fixture in testPublicKeys
|
||||
nativeAlgo string // algorithm actually carried in the key blob
|
||||
askedAlgo string // algorithm passed to parsePubKey
|
||||
}{
|
||||
{"ecdsap256", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384"},
|
||||
{"ecdsap256", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp521"},
|
||||
{"ecdsap384", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp256"},
|
||||
{"ecdsap384", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521"},
|
||||
{"ecdsap521", "ecdsa-sha2-nistp521", "ecdsa-sha2-nistp256"},
|
||||
{"ecdsap521", "ecdsa-sha2-nistp521", "ecdsa-sha2-nistp384"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.nativeAlgo+"_as_"+tc.askedAlgo, func(t *testing.T) {
|
||||
pubKey := testPublicKeys[tc.keyName]
|
||||
algo, in, ok := parseString(pubKey.Marshal())
|
||||
if !ok {
|
||||
t.Fatal("unable to parse public key wire format")
|
||||
}
|
||||
if string(algo) != tc.nativeAlgo {
|
||||
t.Fatalf("test setup failed: expected %q, got %q", tc.nativeAlgo, algo)
|
||||
}
|
||||
|
||||
_, _, err := parsePubKey(in, tc.askedAlgo)
|
||||
if err == nil {
|
||||
t.Fatal("expected error due to algorithm mismatch, but got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "algorithm type mismatch") {
|
||||
t.Fatalf("unexpected error message: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,8 +160,13 @@ func (db *hostKeyDB) IsHostAuthority(remote ssh.PublicKey, address string) bool
|
||||
|
||||
// IsRevoked can be used as a callback in ssh.CertChecker
|
||||
func (db *hostKeyDB) IsRevoked(key *ssh.Certificate) bool {
|
||||
_, ok := db.revoked[string(key.Marshal())]
|
||||
return ok
|
||||
if _, ok := db.revoked[string(key.Marshal())]; ok {
|
||||
return true
|
||||
}
|
||||
if _, ok := db.revoked[string(key.SignatureKey.Marshal())]; ok {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const markerCert = "@cert-authority"
|
||||
@@ -173,7 +178,7 @@ func nextWord(line []byte) (string, []byte) {
|
||||
return string(line), nil
|
||||
}
|
||||
|
||||
return string(line[:i]), bytes.TrimSpace(line[i:])
|
||||
return string(line[:i]), trimSpace(line[i:])
|
||||
}
|
||||
|
||||
func parseLine(line []byte) (marker, host string, key ssh.PublicKey, err error) {
|
||||
@@ -183,12 +188,17 @@ func parseLine(line []byte) (marker, host string, key ssh.PublicKey, err error)
|
||||
}
|
||||
|
||||
host, line = nextWord(line)
|
||||
// If the extracted 'host' starts with '@', it means we either encountered
|
||||
// a second marker (e.g., "@cert-authority @revoked") or an unknown marker
|
||||
// (e.g., "@unknown"). Both are invalid.
|
||||
if len(host) > 0 && host[0] == '@' {
|
||||
return "", "", nil, fmt.Errorf("knownhosts: unexpected marker: %q", host)
|
||||
}
|
||||
if len(line) == 0 {
|
||||
return "", "", nil, errors.New("knownhosts: missing host pattern")
|
||||
}
|
||||
|
||||
// ignore the keytype as it's in the key blob anyway.
|
||||
_, line = nextWord(line)
|
||||
wantType, line := nextWord(line)
|
||||
if len(line) == 0 {
|
||||
return "", "", nil, errors.New("knownhosts: missing key type pattern")
|
||||
}
|
||||
@@ -204,6 +214,10 @@ func parseLine(line []byte) (marker, host string, key ssh.PublicKey, err error)
|
||||
return "", "", nil, err
|
||||
}
|
||||
|
||||
if key.Type() != wantType {
|
||||
return "", "", nil, fmt.Errorf("knownhosts: key type mismatch: found %q, want %q", key.Type(), wantType)
|
||||
}
|
||||
|
||||
return marker, host, key, nil
|
||||
}
|
||||
|
||||
@@ -382,7 +396,7 @@ func (db *hostKeyDB) Read(r io.Reader, filename string) error {
|
||||
for scanner.Scan() {
|
||||
lineNum++
|
||||
line := scanner.Bytes()
|
||||
line = bytes.TrimSpace(line)
|
||||
line = trimSpace(line)
|
||||
if len(line) == 0 || line[0] == '#' {
|
||||
continue
|
||||
}
|
||||
@@ -421,20 +435,26 @@ func New(files ...string) (ssh.HostKeyCallback, error) {
|
||||
return certChecker.CheckHostKey, nil
|
||||
}
|
||||
|
||||
// Normalize normalizes an address into the form used in known_hosts
|
||||
// Normalize normalizes an address into the form used in known_hosts. Supports
|
||||
// IPv4, hostnames, bracketed IPv6. Any other non-standard formats are returned
|
||||
// with minimal transformation.
|
||||
func Normalize(address string) string {
|
||||
const defaultSSHPort = "22"
|
||||
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
host = address
|
||||
port = "22"
|
||||
port = defaultSSHPort
|
||||
}
|
||||
entry := host
|
||||
if port != "22" {
|
||||
entry = "[" + entry + "]:" + port
|
||||
} else if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") {
|
||||
entry = "[" + entry + "]"
|
||||
|
||||
if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
|
||||
host = host[1 : len(host)-1]
|
||||
}
|
||||
return entry
|
||||
|
||||
if port == defaultSSHPort {
|
||||
return host
|
||||
}
|
||||
return "[" + host + "]:" + port
|
||||
}
|
||||
|
||||
// Line returns a line to add append to the known_hosts files.
|
||||
@@ -524,3 +544,10 @@ func newHashedHost(encoded string) (*hashedHost, error) {
|
||||
func (h *hashedHost) match(a addr) bool {
|
||||
return bytes.Equal(hashHost(Normalize(a.String()), h.salt), h.hash)
|
||||
}
|
||||
|
||||
// trimSpace removes leading and trailing ASCII whitespace (space and tab). It
|
||||
// is used instead of bytes.TrimSpace to match OpenSSH behavior, which strictly
|
||||
// parses only ASCII space (0x20) and tab (0x09) as whitespace.
|
||||
func trimSpace(in []byte) []byte {
|
||||
return bytes.Trim(in, " \t")
|
||||
}
|
||||
|
||||
@@ -6,9 +6,13 @@ package knownhosts
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
@@ -236,7 +240,7 @@ func TestLine(t *testing.T) {
|
||||
"server.org": "server.org " + edKeyStr,
|
||||
"server.org:22": "server.org " + edKeyStr,
|
||||
"server.org:23": "[server.org]:23 " + edKeyStr,
|
||||
"[c629:1ec4:102:304:102:304:102:304]:22": "[c629:1ec4:102:304:102:304:102:304] " + edKeyStr,
|
||||
"[c629:1ec4:102:304:102:304:102:304]:22": "c629:1ec4:102:304:102:304:102:304 " + edKeyStr,
|
||||
"[c629:1ec4:102:304:102:304:102:304]:23": "[c629:1ec4:102:304:102:304:102:304]:23 " + edKeyStr,
|
||||
} {
|
||||
if got := Line([]string{in}, edKey); got != want {
|
||||
@@ -272,7 +276,45 @@ func TestWildcardMatch(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO(hanwen): test coverage for certificates.
|
||||
func TestRevokedCA(t *testing.T) {
|
||||
_, caPriv, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
caSigner, err := ssh.NewSignerFromKey(caPriv)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
caKey := caSigner.PublicKey()
|
||||
|
||||
_, hostPriv, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hostKey, err := ssh.NewPublicKey(hostPriv.Public())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cert := &ssh.Certificate{
|
||||
CertType: ssh.HostCert,
|
||||
Key: hostKey,
|
||||
ValidBefore: ssh.CertTimeInfinity,
|
||||
ValidPrincipals: []string{"server.org"},
|
||||
}
|
||||
if err := cert.SignCert(rand.Reader, caSigner); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
caLine := "ssh-ed25519 " + serialize(caKey)[len("ssh-ed25519 "):]
|
||||
knownHostsData := "@revoked server.org " + caLine + "\n" +
|
||||
"@cert-authority server.org " + caLine + "\n"
|
||||
db := testDB(t, knownHostsData)
|
||||
|
||||
if !db.IsRevoked(cert) {
|
||||
t.Error("IsRevoked returned false for certificate signed by revoked CA")
|
||||
}
|
||||
}
|
||||
|
||||
const testHostname = "hostname"
|
||||
|
||||
@@ -310,14 +352,25 @@ func testHostHash(t *testing.T, hostname, encoded string) {
|
||||
|
||||
func TestNormalize(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"127.0.0.1:22": "127.0.0.1",
|
||||
"[127.0.0.1]:22": "127.0.0.1",
|
||||
"[127.0.0.1]:23": "[127.0.0.1]:23",
|
||||
"127.0.0.1:23": "[127.0.0.1]:23",
|
||||
"[a.b.c]:22": "a.b.c",
|
||||
"[abcd:abcd:abcd:abcd]": "[abcd:abcd:abcd:abcd]",
|
||||
"[abcd:abcd:abcd:abcd]:22": "[abcd:abcd:abcd:abcd]",
|
||||
"[abcd:abcd:abcd:abcd]:23": "[abcd:abcd:abcd:abcd]:23",
|
||||
"127.0.0.1": "127.0.0.1",
|
||||
"127.0.0.1:22": "127.0.0.1",
|
||||
"[127.0.0.1]:22": "127.0.0.1",
|
||||
"[127.0.0.1]:23": "[127.0.0.1]:23",
|
||||
"127.0.0.1:23": "[127.0.0.1]:23",
|
||||
"[a.b.c]:22": "a.b.c",
|
||||
"[a.b.c]:23": "[a.b.c]:23",
|
||||
"abcd::abcd:abcd:abcd": "abcd::abcd:abcd:abcd",
|
||||
"[abcd::abcd:abcd:abcd]": "abcd::abcd:abcd:abcd",
|
||||
"[abcd::abcd:abcd:abcd]:22": "abcd::abcd:abcd:abcd",
|
||||
"[abcd::abcd:abcd:abcd]:23": "[abcd::abcd:abcd:abcd]:23",
|
||||
"2001:db8::1": "2001:db8::1",
|
||||
"2001:db8::1:22": "2001:db8::1:22",
|
||||
"[2001:db8::1]:22": "2001:db8::1",
|
||||
"2001:db8::1:2200": "2001:db8::1:2200",
|
||||
"a.b.c.d.com:2200": "[a.b.c.d.com]:2200",
|
||||
"2001::db8:1": "2001::db8:1",
|
||||
"2001::db8:1:22": "2001::db8:1:22",
|
||||
"2001::db8:1:2200": "2001::db8:1:2200",
|
||||
} {
|
||||
got := Normalize(in)
|
||||
if got != want {
|
||||
@@ -356,3 +409,94 @@ func TestIssue36126(t *testing.T) {
|
||||
t.Errorf("should have passed the check, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnicodeSpace(t *testing.T) {
|
||||
line := fmt.Sprintf("server.org %s %s", edKey.Type(), base64.StdEncoding.EncodeToString(edKey.Marshal()))
|
||||
|
||||
db := newHostKeyDB()
|
||||
err := db.Read(bytes.NewBufferString(line), "testdb")
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("Read succeeded on line with Unicode space, expected error due to strict ASCII parsing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnicodeSpaceTrimming(t *testing.T) {
|
||||
const unicodeSpace = " "
|
||||
line := fmt.Sprintf("%sserver.org %s", unicodeSpace, edKeyStr)
|
||||
|
||||
db := newHostKeyDB()
|
||||
err := db.Read(bytes.NewBufferString(line), "testdb")
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Read failed: %v", err)
|
||||
}
|
||||
|
||||
lines := db.lines
|
||||
if len(lines) != 1 {
|
||||
t.Fatalf("Expected 1 line, got %d", len(lines))
|
||||
}
|
||||
|
||||
cleanAddr := addr{host: "server.org", port: "22"}
|
||||
dirtyAddr := addr{host: unicodeSpace + "server.org", port: "22"}
|
||||
|
||||
if lines[0].match(cleanAddr) {
|
||||
t.Errorf("Matched clean host 'server.org', implying Unicode space was trimmed")
|
||||
}
|
||||
if !lines[0].match(dirtyAddr) {
|
||||
t.Errorf("Did not match dirty host, implying parsing issue")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyTypeMismatch(t *testing.T) {
|
||||
line := fmt.Sprintf("server.org ssh-rsa %s", base64.StdEncoding.EncodeToString(edKey.Marshal()))
|
||||
|
||||
db := newHostKeyDB()
|
||||
err := db.Read(bytes.NewBufferString(line), "testdb")
|
||||
if err == nil {
|
||||
t.Fatal("Read succeeded on line with key type mismatch, expected error")
|
||||
}
|
||||
|
||||
expectedErr := `knownhosts: key type mismatch: found "ssh-ed25519", want "ssh-rsa"`
|
||||
if !strings.Contains(err.Error(), expectedErr) {
|
||||
t.Fatalf("got error %q, want to contain %q", err.Error(), expectedErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultipleMarkers(t *testing.T) {
|
||||
lineDouble := fmt.Sprintf("@cert-authority @revoked server.org %s %s", edKey.Type(), base64.StdEncoding.EncodeToString(edKey.Marshal()))
|
||||
db := newHostKeyDB()
|
||||
err := db.Read(bytes.NewBufferString(lineDouble), "testdb")
|
||||
if err == nil {
|
||||
t.Fatal("Read succeeded on line with multiple markers, expected error")
|
||||
}
|
||||
expectedError := "unexpected marker"
|
||||
if !strings.Contains(err.Error(), expectedError) {
|
||||
t.Errorf("got error %q, want it to contain %q", err.Error(), expectedError)
|
||||
}
|
||||
|
||||
lineUnknown := fmt.Sprintf("@unknown-marker server.org %s %s", edKey.Type(), base64.StdEncoding.EncodeToString(edKey.Marshal()))
|
||||
err = db.Read(bytes.NewBufferString(lineUnknown), "testdb")
|
||||
if err == nil {
|
||||
t.Fatal("Read succeeded on line with unknown marker, expected error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), expectedError) {
|
||||
t.Errorf("got error %q, want it to contain %q", err.Error(), expectedError)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownMarker(t *testing.T) {
|
||||
line := fmt.Sprintf("@unknown-marker server.org %s %s", edKey.Type(), base64.StdEncoding.EncodeToString(edKey.Marshal()))
|
||||
|
||||
db := newHostKeyDB()
|
||||
err := db.Read(bytes.NewBufferString(line), "testdb")
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("Read succeeded on line with unknown marker, expected error")
|
||||
}
|
||||
|
||||
expectedError := "unexpected marker"
|
||||
if !strings.Contains(err.Error(), expectedError) {
|
||||
t.Errorf("got error %q, want it to contain %q", err.Error(), expectedError)
|
||||
}
|
||||
}
|
||||
|
||||
+29
-13
@@ -7,11 +7,13 @@ package ssh
|
||||
// Message authentication support
|
||||
|
||||
import (
|
||||
"crypto/fips140"
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"crypto/sha256"
|
||||
"crypto/sha512"
|
||||
"hash"
|
||||
"slices"
|
||||
)
|
||||
|
||||
type macMode struct {
|
||||
@@ -46,23 +48,37 @@ func (t truncatingMAC) Size() int {
|
||||
|
||||
func (t truncatingMAC) BlockSize() int { return t.hmac.BlockSize() }
|
||||
|
||||
var macModes = map[string]*macMode{
|
||||
HMACSHA512ETM: {64, true, func(key []byte) hash.Hash {
|
||||
// macModes defines the supported MACs. MACs not included are not supported
|
||||
// and will not be negotiated, even if explicitly configured. When FIPS mode is
|
||||
// enabled, only FIPS-approved algorithms are included.
|
||||
var macModes = map[string]*macMode{}
|
||||
|
||||
func init() {
|
||||
macModes[HMACSHA512ETM] = &macMode{64, true, func(key []byte) hash.Hash {
|
||||
return hmac.New(sha512.New, key)
|
||||
}},
|
||||
HMACSHA256ETM: {32, true, func(key []byte) hash.Hash {
|
||||
}}
|
||||
macModes[HMACSHA256ETM] = &macMode{32, true, func(key []byte) hash.Hash {
|
||||
return hmac.New(sha256.New, key)
|
||||
}},
|
||||
HMACSHA512: {64, false, func(key []byte) hash.Hash {
|
||||
}}
|
||||
macModes[HMACSHA512] = &macMode{64, false, func(key []byte) hash.Hash {
|
||||
return hmac.New(sha512.New, key)
|
||||
}},
|
||||
HMACSHA256: {32, false, func(key []byte) hash.Hash {
|
||||
}}
|
||||
macModes[HMACSHA256] = &macMode{32, false, func(key []byte) hash.Hash {
|
||||
return hmac.New(sha256.New, key)
|
||||
}},
|
||||
HMACSHA1: {20, false, func(key []byte) hash.Hash {
|
||||
}}
|
||||
|
||||
if fips140.Enabled() {
|
||||
defaultMACs = slices.DeleteFunc(defaultMACs, func(algo string) bool {
|
||||
_, ok := macModes[algo]
|
||||
return !ok
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
macModes[HMACSHA1] = &macMode{20, false, func(key []byte) hash.Hash {
|
||||
return hmac.New(sha1.New, key)
|
||||
}},
|
||||
InsecureHMACSHA196: {20, false, func(key []byte) hash.Hash {
|
||||
}}
|
||||
macModes[InsecureHMACSHA196] = &macMode{20, false, func(key []byte) hash.Hash {
|
||||
return truncatingMAC{12, hmac.New(sha1.New, key)}
|
||||
}},
|
||||
}}
|
||||
}
|
||||
|
||||
+1
-1
@@ -792,7 +792,7 @@ func marshalString(to []byte, s []byte) []byte {
|
||||
return to[len(s):]
|
||||
}
|
||||
|
||||
var bigIntType = reflect.TypeOf((*big.Int)(nil))
|
||||
var bigIntType = reflect.TypeFor[*big.Int]()
|
||||
|
||||
// Decode a packet into its corresponding message.
|
||||
func decode(packet []byte) (interface{}, error) {
|
||||
|
||||
@@ -257,7 +257,7 @@ func TestDecode(t *testing.T) {
|
||||
userAuthSuccess, err := decode([]byte{msgUserAuthSuccess})
|
||||
if err != nil {
|
||||
t.Errorf("error decoding userAuthSuccessMsg")
|
||||
} else if reflect.TypeOf(userAuthSuccess) != reflect.TypeOf((*userAuthSuccessMsg)(nil)) {
|
||||
} else if _, ok := userAuthSuccess.(*userAuthSuccessMsg); !ok {
|
||||
t.Errorf("error decoding userAuthSuccessMsg, unexpected %T", userAuthSuccess)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build go1.24
|
||||
|
||||
package ssh
|
||||
|
||||
import (
|
||||
@@ -13,23 +11,10 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"runtime"
|
||||
"slices"
|
||||
|
||||
"golang.org/x/crypto/curve25519"
|
||||
)
|
||||
|
||||
func init() {
|
||||
// After Go 1.24rc1 mlkem swapped the order of return values of Encapsulate.
|
||||
// See #70950.
|
||||
if runtime.Version() == "go1.24rc1" {
|
||||
return
|
||||
}
|
||||
supportedKexAlgos = slices.Insert(supportedKexAlgos, 0, KeyExchangeMLKEM768X25519)
|
||||
defaultKexAlgos = slices.Insert(defaultKexAlgos, 0, KeyExchangeMLKEM768X25519)
|
||||
kexAlgoMap[KeyExchangeMLKEM768X25519] = &mlkem768WithCurve25519sha256{}
|
||||
}
|
||||
|
||||
// mlkem768WithCurve25519sha256 implements the hybrid ML-KEM768 with
|
||||
// curve25519-sha256 key exchange method, as described by
|
||||
// draft-kampanakis-curdle-ssh-pq-ke-05 section 2.3.3.
|
||||
|
||||
+35
-4
@@ -91,9 +91,10 @@ type mux struct {
|
||||
|
||||
incomingChannels chan NewChannel
|
||||
|
||||
globalSentMu sync.Mutex
|
||||
globalResponses chan interface{}
|
||||
incomingRequests chan *Request
|
||||
globalSentMu sync.Mutex
|
||||
globalSentPending atomic.Bool
|
||||
globalResponses chan interface{}
|
||||
incomingRequests chan *Request
|
||||
|
||||
errCond *sync.Cond
|
||||
err error
|
||||
@@ -141,6 +142,27 @@ func (m *mux) SendRequest(name string, wantReply bool, payload []byte) (bool, []
|
||||
if wantReply {
|
||||
m.globalSentMu.Lock()
|
||||
defer m.globalSentMu.Unlock()
|
||||
|
||||
// Open the gate so that responses arriving while this request is in
|
||||
// flight are allowed to reach globalResponses. Any response arriving
|
||||
// while no request is pending is dropped by handleGlobalPacket.
|
||||
m.globalSentPending.Store(true)
|
||||
defer m.globalSentPending.Store(false)
|
||||
|
||||
// Drain any spurious responses that may have been buffered. This prevents
|
||||
// a previously buffered unexpected response from being consumed instead
|
||||
// of the actual response for this request.
|
||||
drain:
|
||||
for {
|
||||
select {
|
||||
case _, ok := <-m.globalResponses:
|
||||
if !ok {
|
||||
break drain
|
||||
}
|
||||
default:
|
||||
break drain
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := m.sendMessage(globalRequestMsg{
|
||||
@@ -267,7 +289,16 @@ func (m *mux) handleGlobalPacket(packet []byte) error {
|
||||
mux: m,
|
||||
}
|
||||
case *globalRequestSuccessMsg, *globalRequestFailureMsg:
|
||||
m.globalResponses <- msg
|
||||
// Drop responses that arrive when no SendRequest is waiting, to
|
||||
// prevent a malicious peer from staging responses for a future
|
||||
// caller.
|
||||
if !m.globalSentPending.Load() {
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
case m.globalResponses <- msg:
|
||||
default:
|
||||
}
|
||||
default:
|
||||
panic(fmt.Sprintf("not a global message %#v", msg))
|
||||
}
|
||||
|
||||
+606
@@ -10,6 +10,7 @@ import (
|
||||
"io"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func muxPair() (*mux, *mux) {
|
||||
@@ -825,6 +826,50 @@ func TestMuxChannelWindowDeferredUpdates(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMuxChannelRejectRemovesFromMux(t *testing.T) {
|
||||
serverMux, clientMux := muxPair()
|
||||
defer serverMux.Close()
|
||||
defer clientMux.Close()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
t.Cleanup(wg.Wait)
|
||||
wg.Add(1)
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
// The server waits for the channel creation request
|
||||
newCh, ok := <-serverMux.incomingChannels
|
||||
if !ok {
|
||||
t.Error("failed to accept channel")
|
||||
return
|
||||
}
|
||||
ch := newCh.(*channel)
|
||||
|
||||
if serverMux.chanList.getChan(ch.localId) == nil {
|
||||
t.Errorf("channel %d is not in the chanList before Reject", ch.localId)
|
||||
}
|
||||
|
||||
if err := ch.Reject(Prohibited, "rejecting this channel"); err != nil {
|
||||
t.Errorf("Reject failed: %v", err)
|
||||
}
|
||||
|
||||
if serverMux.chanList.getChan(ch.localId) != nil {
|
||||
t.Errorf("channel %d is still in the chanList after Reject", ch.localId)
|
||||
}
|
||||
}()
|
||||
|
||||
_, _, err := clientMux.OpenChannel("test_leak", nil)
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("expected an error (channel rejected), but got nil")
|
||||
}
|
||||
|
||||
if _, ok := err.(*OpenChannelError); !ok {
|
||||
t.Errorf("expected *OpenChannelError, got: %T", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Don't ship code with debug=true.
|
||||
func TestDebug(t *testing.T) {
|
||||
if debugMux {
|
||||
@@ -837,3 +882,564 @@ func TestDebug(t *testing.T) {
|
||||
t.Error("transport debug switched on")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMuxUnexpectedGlobalResponsesDiscarded(t *testing.T) {
|
||||
clientPipe, serverPipe := memPipe()
|
||||
client := newMux(clientPipe)
|
||||
defer serverPipe.Close()
|
||||
defer client.Close()
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
// Send multiple unexpected global responses, this should not block the
|
||||
// globalResponses channel.
|
||||
for i := range 5 {
|
||||
err := serverPipe.writePacket(Marshal(globalRequestSuccessMsg{
|
||||
Data: []byte{byte(i)},
|
||||
}))
|
||||
if err != nil {
|
||||
done <- fmt.Errorf("send success msg %d: %w", i, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
for i := range 5 {
|
||||
err := serverPipe.writePacket(Marshal(globalRequestFailureMsg{
|
||||
Data: []byte{byte(i)},
|
||||
}))
|
||||
if err != nil {
|
||||
done <- fmt.Errorf("send failure msg %d: %w", i, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Now send a global request and wait for the response. This
|
||||
// verifies the mux is still processing packets.
|
||||
err := serverPipe.writePacket(Marshal(globalRequestMsg{
|
||||
Type: "keepalive@golang.org",
|
||||
WantReply: true,
|
||||
Data: nil,
|
||||
}))
|
||||
if err != nil {
|
||||
done <- fmt.Errorf("send global request: %w", err)
|
||||
return
|
||||
}
|
||||
|
||||
packet, err := serverPipe.readPacket()
|
||||
if err != nil {
|
||||
done <- fmt.Errorf("read packet: %w", err)
|
||||
return
|
||||
}
|
||||
decoded, err := decode(packet)
|
||||
if err != nil {
|
||||
done <- fmt.Errorf("decode: %w", err)
|
||||
return
|
||||
}
|
||||
switch decoded.(type) {
|
||||
case *globalRequestSuccessMsg, *globalRequestFailureMsg:
|
||||
// Expected response
|
||||
default:
|
||||
done <- fmt.Errorf("unexpected packet type: %T", decoded)
|
||||
return
|
||||
}
|
||||
done <- nil
|
||||
}()
|
||||
|
||||
// Handle the incoming request from the server and reply
|
||||
req, ok := <-client.incomingRequests
|
||||
if !ok {
|
||||
t.Fatal("incomingRequests channel closed unexpectedly")
|
||||
}
|
||||
if req.Type != "keepalive@golang.org" {
|
||||
t.Fatalf("unexpected request type: %s", req.Type)
|
||||
}
|
||||
if err := req.Reply(true, nil); err != nil {
|
||||
t.Fatalf("Reply: %v", err)
|
||||
}
|
||||
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMuxConcurrentGlobalRequests(t *testing.T) {
|
||||
clientMux, serverMux := muxPair()
|
||||
defer serverMux.Close()
|
||||
defer clientMux.Close()
|
||||
|
||||
const numRequests = 50
|
||||
|
||||
serverDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(serverDone)
|
||||
for r := range serverMux.incomingRequests {
|
||||
if r.WantReply {
|
||||
replyData := append([]byte("reply:"), r.Payload...)
|
||||
r.Reply(true, replyData)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
var clientWg sync.WaitGroup
|
||||
clientWg.Add(numRequests)
|
||||
|
||||
errCh := make(chan error, numRequests)
|
||||
|
||||
for i := range numRequests {
|
||||
go func(id int) {
|
||||
defer clientWg.Done()
|
||||
|
||||
payloadStr := fmt.Sprintf("req-%d", id)
|
||||
payload := []byte(payloadStr)
|
||||
|
||||
// This call blocks until the globalSentMu is acquired.
|
||||
// The mutex ensures that even with many concurrent attempts,
|
||||
// the "drain" and "send" logic happens atomically per request.
|
||||
ok, data, err := clientMux.SendRequest("echo", true, payload)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("req %d error: %v", id, err)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
errCh <- fmt.Errorf("req %d failed (want success)", id)
|
||||
return
|
||||
}
|
||||
|
||||
expected := "reply:" + payloadStr
|
||||
if string(data) != expected {
|
||||
errCh <- fmt.Errorf("req %d mismatch: got %q, want %q", id, string(data), expected)
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
clientWg.Wait()
|
||||
close(errCh)
|
||||
|
||||
for err := range errCh {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
clientMux.Close()
|
||||
<-serverDone
|
||||
}
|
||||
|
||||
func TestMuxGlobalResponseDroppedWhenIdle(t *testing.T) {
|
||||
clientPipe, serverPipe := memPipe()
|
||||
clientMux := newMux(clientPipe)
|
||||
defer serverPipe.Close()
|
||||
defer clientMux.Close()
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
// Send a spurious response while no SendRequest is pending.
|
||||
if err := serverPipe.writePacket(Marshal(globalRequestSuccessMsg{
|
||||
Data: []byte("spurious"),
|
||||
})); err != nil {
|
||||
errCh <- fmt.Errorf("send spurious: %w", err)
|
||||
return
|
||||
}
|
||||
// Follow with a global request; once the client observes this on
|
||||
// incomingRequests, the mux loop has necessarily processed (and
|
||||
// dropped) the prior spurious response.
|
||||
if err := serverPipe.writePacket(Marshal(globalRequestMsg{
|
||||
Type: "sync@example.com",
|
||||
WantReply: false,
|
||||
})); err != nil {
|
||||
errCh <- fmt.Errorf("send sync request: %w", err)
|
||||
return
|
||||
}
|
||||
errCh <- nil
|
||||
}()
|
||||
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req, ok := <-clientMux.incomingRequests
|
||||
if !ok {
|
||||
t.Fatal("incomingRequests closed unexpectedly")
|
||||
}
|
||||
if req.Type != "sync@example.com" {
|
||||
t.Fatalf("unexpected sync request type %q", req.Type)
|
||||
}
|
||||
|
||||
// The spurious response preceded the sync request, so by now the mux
|
||||
// loop has processed it. The pending-gate must have caused it to be
|
||||
// dropped rather than buffered.
|
||||
if n := len(clientMux.globalResponses); n != 0 {
|
||||
t.Fatalf("globalResponses buffer should be empty after idle drop, has %d entries", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMuxStaleResponseDrained(t *testing.T) {
|
||||
// Simulate a stale response sitting in globalResponses (e.g. a response
|
||||
// that slipped in through the pending-gate on a prior SendRequest that
|
||||
// exited without consuming it). The drain step in the next SendRequest
|
||||
// must discard it so the caller receives the correct reply.
|
||||
clientMux, serverMux := muxPair()
|
||||
defer serverMux.Close()
|
||||
defer clientMux.Close()
|
||||
|
||||
clientMux.globalResponses <- &globalRequestSuccessMsg{Data: []byte("stale")}
|
||||
|
||||
serverDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(serverDone)
|
||||
for req := range serverMux.incomingRequests {
|
||||
if req.WantReply {
|
||||
req.Reply(true, append([]byte("reply:"), req.Payload...))
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
ok, data, err := clientMux.SendRequest("test", true, []byte("hello"))
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
if !ok {
|
||||
t.Fatal("expected success response")
|
||||
}
|
||||
if string(data) != "reply:hello" {
|
||||
t.Fatalf("got %q, want %q (drain did not remove stale response)", data, "reply:hello")
|
||||
}
|
||||
|
||||
clientMux.Close()
|
||||
<-serverDone
|
||||
}
|
||||
|
||||
func TestMuxGlobalResponseAcceptedWhilePending(t *testing.T) {
|
||||
// Positive control: when a SendRequest is actually pending, the
|
||||
// response must be delivered (the gate is open).
|
||||
clientMux, serverMux := muxPair()
|
||||
defer serverMux.Close()
|
||||
defer clientMux.Close()
|
||||
|
||||
serverDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(serverDone)
|
||||
for req := range serverMux.incomingRequests {
|
||||
if req.WantReply {
|
||||
req.Reply(true, []byte("pong"))
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
ok, data, err := clientMux.SendRequest("ping", true, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("SendRequest: %v", err)
|
||||
}
|
||||
if !ok || string(data) != "pong" {
|
||||
t.Fatalf("unexpected response: ok=%v data=%q", ok, data)
|
||||
}
|
||||
|
||||
clientMux.Close()
|
||||
<-serverDone
|
||||
}
|
||||
|
||||
func TestChannelUnexpectedResponsesDiscarded(t *testing.T) {
|
||||
// A malicious peer that spams channelRequestSuccess/Failure messages
|
||||
// for an open, idle channel must not be able to stall the mux read
|
||||
// loop by filling ch.msg. After the flood, the channel must still be
|
||||
// usable: a subsequent legitimate SendRequest receives its reply.
|
||||
clientMux, serverMux := muxPair()
|
||||
defer serverMux.Close()
|
||||
defer clientMux.Close()
|
||||
|
||||
serverRes := make(chan *channel, 1)
|
||||
go func() {
|
||||
newCh, ok := <-serverMux.incomingChannels
|
||||
if !ok {
|
||||
close(serverRes)
|
||||
return
|
||||
}
|
||||
c, _, err := newCh.Accept()
|
||||
if err != nil {
|
||||
close(serverRes)
|
||||
return
|
||||
}
|
||||
serverRes <- c.(*channel)
|
||||
}()
|
||||
|
||||
clientCh, err := clientMux.openChannel("chan", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("openChannel: %v", err)
|
||||
}
|
||||
serverCh := <-serverRes
|
||||
if serverCh == nil {
|
||||
t.Fatal("server did not accept channel")
|
||||
}
|
||||
|
||||
// Spam many unsolicited success/failure responses. More than chanSize
|
||||
// to ensure ch.msg would overflow without the pending-gate.
|
||||
const spam = chanSize * 4
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
for i := range spam {
|
||||
if err := serverCh.ackRequest(i%2 == 0); err != nil {
|
||||
done <- fmt.Errorf("ackRequest %d: %w", i, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
// Echo any legitimate request back.
|
||||
for req := range serverCh.incomingRequests {
|
||||
if req.WantReply {
|
||||
if err := req.Reply(true, append([]byte("reply:"), req.Payload...)); err != nil {
|
||||
done <- fmt.Errorf("reply: %w", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
done <- nil
|
||||
}()
|
||||
|
||||
// If the flood had wedged the mux loop, this SendRequest would never
|
||||
// receive a reply.
|
||||
ok, err := clientCh.SendRequest("ping", true, []byte("hello"))
|
||||
if err != nil {
|
||||
t.Fatalf("SendRequest: %v", err)
|
||||
}
|
||||
if !ok {
|
||||
t.Fatal("expected success reply")
|
||||
}
|
||||
|
||||
// Clean up so the server goroutine can exit.
|
||||
clientCh.Close()
|
||||
serverCh.Close()
|
||||
if err := <-done; err != nil {
|
||||
if !errors.Is(err, io.EOF) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelConcurrentRequests(t *testing.T) {
|
||||
writer, reader, mux := channelPair(t)
|
||||
defer writer.Close()
|
||||
defer reader.Close()
|
||||
defer mux.Close()
|
||||
|
||||
serverDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(serverDone)
|
||||
for req := range writer.incomingRequests {
|
||||
if req.WantReply {
|
||||
req.Reply(true, append([]byte("reply:"), req.Payload...))
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
const numRequests = 50
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(numRequests)
|
||||
errCh := make(chan error, numRequests)
|
||||
|
||||
for i := 0; i < numRequests; i++ {
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
payload := []byte(fmt.Sprintf("req-%d", id))
|
||||
ok, err := reader.SendRequest("echo", true, payload)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("req %d: %v", id, err)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
errCh <- fmt.Errorf("req %d: expected success", id)
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
close(errCh)
|
||||
|
||||
for err := range errCh {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
reader.Close()
|
||||
writer.Close()
|
||||
<-serverDone
|
||||
}
|
||||
|
||||
func TestChannelResponseDroppedWhenIdle(t *testing.T) {
|
||||
// A spurious response arriving while no SendRequest is pending must
|
||||
// be dropped rather than buffered in ch.msg.
|
||||
writer, reader, mux := channelPair(t)
|
||||
defer writer.Close()
|
||||
defer reader.Close()
|
||||
defer mux.Close()
|
||||
|
||||
// Server sends an unsolicited reply, then a request so we can
|
||||
// synchronise: once the client observes the request, the mux loop has
|
||||
// necessarily processed (and dropped) the prior spurious reply.
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
if err := writer.ackRequest(true); err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
if _, err := writer.SendRequest("sync", false, nil); err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
errCh <- nil
|
||||
}()
|
||||
|
||||
req := <-reader.incomingRequests
|
||||
if req.Type != "sync" {
|
||||
t.Fatalf("unexpected request type %q", req.Type)
|
||||
}
|
||||
|
||||
if n := len(reader.msg); n != 0 {
|
||||
t.Fatalf("ch.msg should be empty after idle drop, has %d entries", n)
|
||||
}
|
||||
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelStaleResponseDrained(t *testing.T) {
|
||||
// Simulate a stale response sitting in ch.msg (e.g. a response that
|
||||
// slipped through the pending-gate on a prior SendRequest that exited
|
||||
// without consuming it). The drain step in the next SendRequest must
|
||||
// discard it so the caller receives the correct reply.
|
||||
writer, reader, mux := channelPair(t)
|
||||
defer writer.Close()
|
||||
defer reader.Close()
|
||||
defer mux.Close()
|
||||
|
||||
reader.msg <- &channelRequestSuccessMsg{PeersID: reader.remoteId}
|
||||
|
||||
serverDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(serverDone)
|
||||
for req := range writer.incomingRequests {
|
||||
if req.WantReply {
|
||||
req.Reply(false, append([]byte("nack:"), req.Payload...))
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
ok, err := reader.SendRequest("test", true, []byte("hello"))
|
||||
if err != nil {
|
||||
t.Fatalf("SendRequest: %v", err)
|
||||
}
|
||||
// If the stale success had been consumed, ok would be true.
|
||||
if ok {
|
||||
t.Fatal("got stale success response; drain did not remove it")
|
||||
}
|
||||
|
||||
reader.Close()
|
||||
writer.Close()
|
||||
<-serverDone
|
||||
}
|
||||
|
||||
func TestChannelResponseAcceptedWhilePending(t *testing.T) {
|
||||
// Positive control: when a SendRequest is actually pending, the
|
||||
// response must be delivered (the gate is open).
|
||||
writer, reader, mux := channelPair(t)
|
||||
defer writer.Close()
|
||||
defer reader.Close()
|
||||
defer mux.Close()
|
||||
|
||||
serverDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(serverDone)
|
||||
for req := range writer.incomingRequests {
|
||||
if req.WantReply {
|
||||
req.Reply(true, nil)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
ok, err := reader.SendRequest("ping", true, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("SendRequest: %v", err)
|
||||
}
|
||||
if !ok {
|
||||
t.Fatal("expected success")
|
||||
}
|
||||
|
||||
reader.Close()
|
||||
writer.Close()
|
||||
<-serverDone
|
||||
}
|
||||
|
||||
func TestChannelSendRequestAfterCloseNoSpinloop(t *testing.T) {
|
||||
writer, reader, mux := channelPair(t)
|
||||
defer writer.Close()
|
||||
defer mux.Close()
|
||||
|
||||
// Close the channel, this closes reader.msg.
|
||||
if err := reader.Close(); err != nil {
|
||||
t.Fatalf("Close: %v", err)
|
||||
}
|
||||
// Wait for reader.msg to actually be closed by the mux loop.
|
||||
for {
|
||||
select {
|
||||
case _, ok := <-reader.msg:
|
||||
if !ok {
|
||||
goto closed
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("reader.msg was not closed")
|
||||
}
|
||||
}
|
||||
closed:
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := reader.SendRequest("ping", true, nil)
|
||||
done <- err
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, io.EOF) {
|
||||
t.Fatalf("SendRequest after close: got %v, want io.EOF", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("SendRequest spinloop on closed ch.msg")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMuxSendRequestAfterCloseNoSpinloop(t *testing.T) {
|
||||
a, b := muxPair()
|
||||
defer a.Close()
|
||||
|
||||
// Closing the underlying conn causes mux.loop to exit and close
|
||||
// b.globalResponses.
|
||||
if err := b.Close(); err != nil {
|
||||
t.Fatalf("Close: %v", err)
|
||||
}
|
||||
// Wait for globalResponses to actually be closed by loop().
|
||||
for {
|
||||
select {
|
||||
case _, ok := <-b.globalResponses:
|
||||
if !ok {
|
||||
goto closed
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("globalResponses was not closed")
|
||||
}
|
||||
}
|
||||
closed:
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, _, err := b.SendRequest("ping", true, nil)
|
||||
done <- err
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
if err == nil {
|
||||
t.Fatal("SendRequest after close: got nil error")
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("SendRequest spinloop on closed globalResponses")
|
||||
}
|
||||
}
|
||||
|
||||
+179
-22
@@ -10,6 +10,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -33,18 +34,29 @@ type Permissions struct {
|
||||
// or not supported.
|
||||
CriticalOptions map[string]string
|
||||
|
||||
// Extensions are extra functionality that the server may
|
||||
// offer on authenticated connections. Lack of support for an
|
||||
// extension does not preclude authenticating a user. Common
|
||||
// extensions are "permit-agent-forwarding",
|
||||
// "permit-X11-forwarding". The Go SSH library currently does
|
||||
// not act on any extension, and it is up to server
|
||||
// implementations to honor them. Extensions can be used to
|
||||
// pass data from the authentication callbacks to the server
|
||||
// application layer.
|
||||
// Extensions are extra functionality that the server may offer on
|
||||
// authenticated connections. Lack of support for an extension does not
|
||||
// preclude authenticating a user. Common extensions are
|
||||
// "permit-agent-forwarding", "permit-X11-forwarding". In general the Go
|
||||
// SSH library does not act on extensions and it is up to server
|
||||
// implementations to honor them; extensions can also be used to pass data
|
||||
// from the authentication callbacks to the server application layer.
|
||||
//
|
||||
// The one extension acted upon by this library is "no-touch-required",
|
||||
// which applies only to security-key public keys
|
||||
// (sk-ecdsa-sha2-nistp256@openssh.com and sk-ssh-ed25519@openssh.com).
|
||||
// When present, it waives the default requirement that SK signatures
|
||||
// assert user presence (i.e. a physical touch of the authenticator)
|
||||
// during signature verification.
|
||||
Extensions map[string]string
|
||||
|
||||
// ExtraData allows to store user defined data.
|
||||
ExtraData map[any]any
|
||||
}
|
||||
|
||||
// GSSAPIWithMICConfig includes the server callbacks for gssapi-with-mic
|
||||
// authentication. If either field is nil, gssapi-with-mic is considered not
|
||||
// configured.
|
||||
type GSSAPIWithMICConfig struct {
|
||||
// AllowLogin, must be set, is called when gssapi-with-mic
|
||||
// authentication is selected (RFC 4462 section 3). The srcName is from the
|
||||
@@ -59,6 +71,10 @@ type GSSAPIWithMICConfig struct {
|
||||
Server GSSAPIServer
|
||||
}
|
||||
|
||||
func gssapiWithMICConfigured(config *GSSAPIWithMICConfig) bool {
|
||||
return config != nil && config.AllowLogin != nil && config.Server != nil
|
||||
}
|
||||
|
||||
// SendAuthBanner implements [ServerPreAuthConn].
|
||||
func (s *connection) SendAuthBanner(msg string) error {
|
||||
return s.transport.writePacket(Marshal(&userAuthBannerMsg{
|
||||
@@ -80,6 +96,79 @@ type ServerPreAuthConn interface {
|
||||
SendAuthBanner(string) error
|
||||
}
|
||||
|
||||
// noTouchRequiredExtension is the extension name used by OpenSSH in
|
||||
// authorized_keys options and certificate extensions to mark keys
|
||||
// whose signatures do not need to assert user presence (touch). See
|
||||
// ssh-keygen(1) and sshd(8).
|
||||
const noTouchRequiredExtension = "no-touch-required"
|
||||
|
||||
// noTouchAllowed reports whether the user presence requirement on
|
||||
// SK signatures should be waived for this authentication attempt. The
|
||||
// requirement is waived when the "no-touch-required" extension is
|
||||
// present either in the Permissions returned by the auth callback
|
||||
// (authorized_keys-level opt-out) or in the certificate's own
|
||||
// Extensions (CA-level opt-out), matching OpenSSH behavior. OpenSSH
|
||||
// reads the per-key opt-out only from cert Extensions and
|
||||
// authorized_keys options (never from CriticalOptions); we follow the
|
||||
// same rule.
|
||||
func noTouchAllowed(pubKey PublicKey, perms *Permissions) bool {
|
||||
if perms != nil {
|
||||
if _, ok := perms.Extensions[noTouchRequiredExtension]; ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if cert, ok := pubKey.(*Certificate); ok {
|
||||
if _, ok := cert.Extensions[noTouchRequiredExtension]; ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// skKeyWithoutUP returns a PublicKey equivalent to pubKey but whose
|
||||
// Verify accepts SK signatures with the user-presence flag clear. If
|
||||
// pubKey is not (and does not wrap) an SK key, pubKey is returned
|
||||
// unchanged. The returned value never mutates pubKey: for SK keys a
|
||||
// shallow copy is made so that the noTouchRequired flag is set only on
|
||||
// the clone.
|
||||
//
|
||||
// The implementation is iterative rather than recursive. When pubKey
|
||||
// is a *Certificate we unwrap exactly one level to look at the inner
|
||||
// key. The SSH cert format forbids Certificate.Key from being another
|
||||
// Certificate (parseCert rejects it), but nothing stops callers from
|
||||
// constructing such a value directly in Go; a recursive descent could
|
||||
// otherwise be driven to unbounded depth by a hand-crafted or cyclic
|
||||
// Certificate. A malformed input of that shape simply returns
|
||||
// unchanged here.
|
||||
func skKeyWithoutUP(pubKey PublicKey) PublicKey {
|
||||
cert, isCert := pubKey.(*Certificate)
|
||||
target := pubKey
|
||||
if isCert {
|
||||
target = cert.Key
|
||||
}
|
||||
var cloned PublicKey
|
||||
switch k := target.(type) {
|
||||
case *skECDSAPublicKey:
|
||||
c := *k
|
||||
c.noTouchRequired = true
|
||||
cloned = &c
|
||||
case *skEd25519PublicKey:
|
||||
c := *k
|
||||
c.noTouchRequired = true
|
||||
cloned = &c
|
||||
default:
|
||||
// Not an SK key (or a pathological *Certificate wrapping
|
||||
// another *Certificate): pubKey is already usable for Verify.
|
||||
return pubKey
|
||||
}
|
||||
if !isCert {
|
||||
return cloned
|
||||
}
|
||||
c := *cert
|
||||
c.Key = cloned
|
||||
return &c
|
||||
}
|
||||
|
||||
// ServerConfig holds server specific configuration data.
|
||||
type ServerConfig struct {
|
||||
// Config contains configuration shared between client and server.
|
||||
@@ -126,6 +215,21 @@ type ServerConfig struct {
|
||||
// Permissions.Extensions entry.
|
||||
PublicKeyCallback func(conn ConnMetadata, key PublicKey) (*Permissions, error)
|
||||
|
||||
// VerifiedPublicKeyCallback, if non-nil, is called after a client
|
||||
// successfully confirms having control over a key that was previously
|
||||
// approved by PublicKeyCallback. The permissions object passed to the
|
||||
// callback is the one returned by PublicKeyCallback for the given public
|
||||
// key and its ownership is transferred to the callback. The returned
|
||||
// Permissions object can be the same object, optionally modified, or a
|
||||
// completely new object. If VerifiedPublicKeyCallback is non-nil,
|
||||
// PublicKeyCallback is not allowed to return a PartialSuccessError, which
|
||||
// can instead be returned by VerifiedPublicKeyCallback.
|
||||
//
|
||||
// VerifiedPublicKeyCallback does not affect which authentication methods
|
||||
// are included in the list of methods that can be attempted by the client.
|
||||
VerifiedPublicKeyCallback func(conn ConnMetadata, key PublicKey, permissions *Permissions,
|
||||
signatureAlgorithm string) (*Permissions, error)
|
||||
|
||||
// KeyboardInteractiveCallback, if non-nil, is called when
|
||||
// keyboard-interactive authentication is selected (RFC
|
||||
// 4256). The client object's Challenge function should be
|
||||
@@ -223,8 +327,10 @@ func (c *pubKeyCache) add(candidate cachedPubKey) {
|
||||
type ServerConn struct {
|
||||
Conn
|
||||
|
||||
// If the succeeding authentication callback returned a
|
||||
// non-nil Permissions pointer, it is stored here.
|
||||
// If the succeeding authentication callback returned a non-nil Permissions
|
||||
// pointer, it is stored here. These are the permissions from the final,
|
||||
// successful authentication method. Permissions returned by callbacks that
|
||||
// return PartialSuccessError are not preserved and must be nil.
|
||||
Permissions *Permissions
|
||||
}
|
||||
|
||||
@@ -246,7 +352,7 @@ func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewCha
|
||||
fullConf.PublicKeyAuthAlgorithms = defaultPubKeyAuthAlgos
|
||||
} else {
|
||||
for _, algo := range fullConf.PublicKeyAuthAlgorithms {
|
||||
if !contains(SupportedAlgorithms().PublicKeyAuths, algo) && !contains(InsecureAlgorithms().PublicKeyAuths, algo) {
|
||||
if !slices.Contains(SupportedAlgorithms().PublicKeyAuths, algo) && !slices.Contains(InsecureAlgorithms().PublicKeyAuths, algo) {
|
||||
c.Close()
|
||||
return nil, nil, nil, fmt.Errorf("ssh: unsupported public key authentication algorithm %s", algo)
|
||||
}
|
||||
@@ -283,8 +389,7 @@ func (s *connection) serverHandshake(config *ServerConfig) (*Permissions, error)
|
||||
}
|
||||
|
||||
if !config.NoClientAuth && config.PasswordCallback == nil && config.PublicKeyCallback == nil &&
|
||||
config.KeyboardInteractiveCallback == nil && (config.GSSAPIWithMICConfig == nil ||
|
||||
config.GSSAPIWithMICConfig.AllowLogin == nil || config.GSSAPIWithMICConfig.Server == nil) {
|
||||
config.KeyboardInteractiveCallback == nil && !gssapiWithMICConfigured(config.GSSAPIWithMICConfig) {
|
||||
return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
|
||||
}
|
||||
|
||||
@@ -508,6 +613,15 @@ func (b *BannerError) Error() string {
|
||||
return b.Err.Error()
|
||||
}
|
||||
|
||||
// maxAuthServerAttempts caps the total number of SSH_MSG_USERAUTH_REQUEST
|
||||
// messages the server will process on a single connection, regardless of
|
||||
// outcome (failure, partial success, public key query, or none). It is a
|
||||
// backstop against clients that drive the authentication loop indefinitely
|
||||
// without ever incurring a real failure — for example by repeatedly
|
||||
// triggering PartialSuccessError or by spamming public key offer queries —
|
||||
// neither of which increment the MaxAuthTries failure counter.
|
||||
const maxAuthServerAttempts = 128
|
||||
|
||||
func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, error) {
|
||||
if config.PreAuthConnCallback != nil {
|
||||
config.PreAuthConnCallback(s)
|
||||
@@ -518,6 +632,7 @@ func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, err
|
||||
var perms *Permissions
|
||||
|
||||
authFailures := 0
|
||||
authAttempts := 0
|
||||
noneAuthCount := 0
|
||||
var authErrs []error
|
||||
var calledBannerCallback bool
|
||||
@@ -546,6 +661,19 @@ userAuthLoop:
|
||||
return nil, &ServerAuthError{Errors: authErrs}
|
||||
}
|
||||
|
||||
if authAttempts >= maxAuthServerAttempts {
|
||||
discMsg := &disconnectMsg{
|
||||
Reason: 2,
|
||||
Message: "too many authentication attempts",
|
||||
}
|
||||
if err := s.transport.writePacket(Marshal(discMsg)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authErrs = append(authErrs, discMsg)
|
||||
return nil, &ServerAuthError{Errors: authErrs}
|
||||
}
|
||||
authAttempts++
|
||||
|
||||
var userAuthReq userAuthRequestMsg
|
||||
if packet, err := s.transport.readPacket(); err != nil {
|
||||
if err == io.EOF {
|
||||
@@ -631,7 +759,7 @@ userAuthLoop:
|
||||
return nil, parseError(msgUserAuthRequest)
|
||||
}
|
||||
algo := string(algoBytes)
|
||||
if !contains(config.PublicKeyAuthAlgorithms, underlyingAlgo(algo)) {
|
||||
if !slices.Contains(config.PublicKeyAuthAlgorithms, underlyingAlgo(algo)) {
|
||||
authErr = fmt.Errorf("ssh: algorithm %q not accepted", algo)
|
||||
break
|
||||
}
|
||||
@@ -652,6 +780,9 @@ userAuthLoop:
|
||||
candidate.pubKeyData = pubKeyData
|
||||
candidate.perms, candidate.result = authConfig.PublicKeyCallback(s, pubKey)
|
||||
_, isPartialSuccessError := candidate.result.(*PartialSuccessError)
|
||||
if isPartialSuccessError && config.VerifiedPublicKeyCallback != nil {
|
||||
return nil, errors.New("ssh: invalid library usage: PublicKeyCallback must not return partial success when VerifiedPublicKeyCallback is defined")
|
||||
}
|
||||
|
||||
if (candidate.result == nil || isPartialSuccessError) &&
|
||||
candidate.perms != nil &&
|
||||
@@ -695,7 +826,7 @@ userAuthLoop:
|
||||
// ssh-rsa-cert-v01@openssh.com algorithm with ssh-rsa public
|
||||
// key type. The algorithm and public key type must be
|
||||
// consistent: both must be certificate algorithms, or neither.
|
||||
if !contains(algorithmsForKeyFormat(pubKey.Type()), algo) {
|
||||
if !slices.Contains(algorithmsForKeyFormat(pubKey.Type()), algo) {
|
||||
authErr = fmt.Errorf("ssh: public key type %q not compatible with selected algorithm %q",
|
||||
pubKey.Type(), algo)
|
||||
break
|
||||
@@ -705,7 +836,7 @@ userAuthLoop:
|
||||
// algorithm name that corresponds to algo with
|
||||
// sig.Format. This is usually the same, but
|
||||
// for certs, the names differ.
|
||||
if !contains(config.PublicKeyAuthAlgorithms, sig.Format) {
|
||||
if !slices.Contains(config.PublicKeyAuthAlgorithms, sig.Format) {
|
||||
authErr = fmt.Errorf("ssh: algorithm %q not accepted", sig.Format)
|
||||
break
|
||||
}
|
||||
@@ -715,16 +846,36 @@ userAuthLoop:
|
||||
}
|
||||
|
||||
signedData := buildDataSignedForAuth(sessionID, userAuthReq, algo, pubKeyData)
|
||||
|
||||
if err := pubKey.Verify(signedData, sig); err != nil {
|
||||
// pubKey is reused below for VerifiedPublicKeyCallback and
|
||||
// must remain the key as presented by the client; derive a
|
||||
// separate value for Verify that carries any applicable
|
||||
// no-touch-required opt-out.
|
||||
pubKeyForVerify := pubKey
|
||||
if noTouchAllowed(pubKey, candidate.perms) {
|
||||
pubKeyForVerify = skKeyWithoutUP(pubKey)
|
||||
}
|
||||
if err := pubKeyForVerify.Verify(signedData, sig); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
authErr = candidate.result
|
||||
perms = candidate.perms
|
||||
if authErr == nil && config.VerifiedPublicKeyCallback != nil {
|
||||
// Only call VerifiedPublicKeyCallback after the key has been accepted
|
||||
// and successfully verified. If authErr is non-nil, the key is not
|
||||
// considered verified and the callback must not run.
|
||||
perms, authErr = config.VerifiedPublicKeyCallback(s, pubKey, perms, algo)
|
||||
}
|
||||
if authErr == nil && perms != nil && perms.CriticalOptions != nil {
|
||||
if saco := perms.CriticalOptions[sourceAddressCriticalOption]; saco != "" {
|
||||
if err := checkSourceAddress(s.RemoteAddr(), saco); err != nil {
|
||||
authErr = err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
case "gssapi-with-mic":
|
||||
if authConfig.GSSAPIWithMICConfig == nil {
|
||||
if !gssapiWithMICConfigured(authConfig.GSSAPIWithMICConfig) {
|
||||
authErr = errors.New("ssh: gssapi-with-mic auth not configured")
|
||||
break
|
||||
}
|
||||
@@ -796,6 +947,13 @@ userAuthLoop:
|
||||
var failureMsg userAuthFailureMsg
|
||||
|
||||
if partialSuccess, ok := authErr.(*PartialSuccessError); ok {
|
||||
// Permissions are not preserved between authentication steps. To
|
||||
// avoid confusion about the final state of the connection, we
|
||||
// disallow returning non-nil Permissions combined with
|
||||
// PartialSuccessError.
|
||||
if perms != nil {
|
||||
return nil, errors.New("ssh: permissions must be nil when returning PartialSuccessError")
|
||||
}
|
||||
// After a partial success error we don't allow changing the user
|
||||
// name and execute the NoClientAuthCallback.
|
||||
partialSuccessReturned = true
|
||||
@@ -850,8 +1008,7 @@ userAuthLoop:
|
||||
if authConfig.KeyboardInteractiveCallback != nil {
|
||||
failureMsg.Methods = append(failureMsg.Methods, "keyboard-interactive")
|
||||
}
|
||||
if authConfig.GSSAPIWithMICConfig != nil && authConfig.GSSAPIWithMICConfig.Server != nil &&
|
||||
authConfig.GSSAPIWithMICConfig.AllowLogin != nil {
|
||||
if gssapiWithMICConfigured(authConfig.GSSAPIWithMICConfig) {
|
||||
failureMsg.Methods = append(failureMsg.Methods, "gssapi-with-mic")
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user