...

Source file src/golang.org/x/crypto/ssh/test/cert_test.go

Documentation: golang.org/x/crypto/ssh/test

     1  // Copyright 2014 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
     6  
     7  package test
     8  
     9  import (
    10  	"bytes"
    11  	"crypto/rand"
    12  	"testing"
    13  
    14  	"golang.org/x/crypto/ssh"
    15  )
    16  
    17  // Test both logging in with a cert, and also that the certificate presented by an OpenSSH host can be validated correctly
    18  func TestCertLogin(t *testing.T) {
    19  	s := newServer(t)
    20  
    21  	// Use a key different from the default.
    22  	clientKey := testSigners["dsa"]
    23  	caAuthKey := testSigners["ecdsa"]
    24  	cert := &ssh.Certificate{
    25  		Key:             clientKey.PublicKey(),
    26  		ValidPrincipals: []string{username()},
    27  		CertType:        ssh.UserCert,
    28  		ValidBefore:     ssh.CertTimeInfinity,
    29  	}
    30  	if err := cert.SignCert(rand.Reader, caAuthKey); err != nil {
    31  		t.Fatalf("SetSignature: %v", err)
    32  	}
    33  
    34  	certSigner, err := ssh.NewCertSigner(cert, clientKey)
    35  	if err != nil {
    36  		t.Fatalf("NewCertSigner: %v", err)
    37  	}
    38  
    39  	conf := &ssh.ClientConfig{
    40  		User: username(),
    41  		HostKeyCallback: (&ssh.CertChecker{
    42  			IsHostAuthority: func(pk ssh.PublicKey, addr string) bool {
    43  				return bytes.Equal(pk.Marshal(), testPublicKeys["ca"].Marshal())
    44  			},
    45  		}).CheckHostKey,
    46  	}
    47  	conf.Auth = append(conf.Auth, ssh.PublicKeys(certSigner))
    48  
    49  	for _, test := range []struct {
    50  		addr    string
    51  		succeed bool
    52  	}{
    53  		{addr: "host.example.com:22", succeed: true},
    54  		{addr: "host.example.com:10000", succeed: true}, // non-standard port must be OK
    55  		{addr: "host.example.com", succeed: false},      // port must be specified
    56  		{addr: "host.ex4mple.com:22", succeed: false},   // wrong host
    57  	} {
    58  		client, err := s.TryDialWithAddr(conf, test.addr)
    59  
    60  		// Always close client if opened successfully
    61  		if err == nil {
    62  			client.Close()
    63  		}
    64  
    65  		// Now evaluate whether the test failed or passed
    66  		if test.succeed {
    67  			if err != nil {
    68  				t.Fatalf("TryDialWithAddr: %v", err)
    69  			}
    70  		} else {
    71  			if err == nil {
    72  				t.Fatalf("TryDialWithAddr, unexpected success")
    73  			}
    74  		}
    75  	}
    76  }
    77  

View as plain text