github.com/Psiphon-Labs/psiphon-tunnel-core@v2.0.28+incompatible/psiphon/common/crypto/ssh/certs_test.go (about)

     1  // Copyright 2013 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  package ssh
     6  
     7  import (
     8  	"bytes"
     9  	"crypto/ecdsa"
    10  	"crypto/elliptic"
    11  	"crypto/rand"
    12  	"fmt"
    13  	"io"
    14  	"net"
    15  	"reflect"
    16  	"testing"
    17  	"time"
    18  )
    19  
    20  // Cert generated by ssh-keygen 6.0p1 Debian-4.
    21  // % ssh-keygen -s ca-key -I test user-key
    22  const exampleSSHCert = `ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgb1srW/W3ZDjYAO45xLYAwzHBDLsJ4Ux6ICFIkTjb1LEAAAADAQABAAAAYQCkoR51poH0wE8w72cqSB8Sszx+vAhzcMdCO0wqHTj7UNENHWEXGrU0E0UQekD7U+yhkhtoyjbPOVIP7hNa6aRk/ezdh/iUnCIt4Jt1v3Z1h1P+hA4QuYFMHNB+rmjPwAcAAAAAAAAAAAAAAAEAAAAEdGVzdAAAAAAAAAAAAAAAAP//////////AAAAAAAAAIIAAAAVcGVybWl0LVgxMS1mb3J3YXJkaW5nAAAAAAAAABdwZXJtaXQtYWdlbnQtZm9yd2FyZGluZwAAAAAAAAAWcGVybWl0LXBvcnQtZm9yd2FyZGluZwAAAAAAAAAKcGVybWl0LXB0eQAAAAAAAAAOcGVybWl0LXVzZXItcmMAAAAAAAAAAAAAAHcAAAAHc3NoLXJzYQAAAAMBAAEAAABhANFS2kaktpSGc+CcmEKPyw9mJC4nZKxHKTgLVZeaGbFZOvJTNzBspQHdy7Q1uKSfktxpgjZnksiu/tFF9ngyY2KFoc+U88ya95IZUycBGCUbBQ8+bhDtw/icdDGQD5WnUwAAAG8AAAAHc3NoLXJzYQAAAGC8Y9Z2LQKhIhxf52773XaWrXdxP0t3GBVo4A10vUWiYoAGepr6rQIoGGXFxT4B9Gp+nEBJjOwKDXPrAevow0T9ca8gZN+0ykbhSrXLE5Ao48rqr3zP4O1/9P7e6gp0gw8=`
    23  
    24  func TestParseCert(t *testing.T) {
    25  	authKeyBytes := []byte(exampleSSHCert)
    26  
    27  	key, _, _, rest, err := ParseAuthorizedKey(authKeyBytes)
    28  	if err != nil {
    29  		t.Fatalf("ParseAuthorizedKey: %v", err)
    30  	}
    31  	if len(rest) > 0 {
    32  		t.Errorf("rest: got %q, want empty", rest)
    33  	}
    34  
    35  	if _, ok := key.(*Certificate); !ok {
    36  		t.Fatalf("got %v (%T), want *Certificate", key, key)
    37  	}
    38  
    39  	marshaled := MarshalAuthorizedKey(key)
    40  	// Before comparison, remove the trailing newline that
    41  	// MarshalAuthorizedKey adds.
    42  	marshaled = marshaled[:len(marshaled)-1]
    43  	if !bytes.Equal(authKeyBytes, marshaled) {
    44  		t.Errorf("marshaled certificate does not match original: got %q, want %q", marshaled, authKeyBytes)
    45  	}
    46  }
    47  
    48  // Cert generated by ssh-keygen OpenSSH_6.8p1 OS X 10.10.3
    49  // % ssh-keygen -s ca -I testcert -O source-address=192.168.1.0/24 -O force-command=/bin/sleep user.pub
    50  // user.pub key: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDACh1rt2DXfV3hk6fszSQcQ/rueMId0kVD9U7nl8cfEnFxqOCrNT92g4laQIGl2mn8lsGZfTLg8ksHq3gkvgO3oo/0wHy4v32JeBOHTsN5AL4gfHNEhWeWb50ev47hnTsRIt9P4dxogeUo/hTu7j9+s9lLpEQXCvq6xocXQt0j8MV9qZBBXFLXVT3cWIkSqOdwt/5ZBg+1GSrc7WfCXVWgTk4a20uPMuJPxU4RQwZW6X3+O8Pqo8C3cW0OzZRFP6gUYUKUsTI5WntlS+LAxgw1mZNsozFGdbiOPRnEryE3SRldh9vjDR3tin1fGpA5P7+CEB/bqaXtG3V+F2OkqaMN
    51  // Critical Options:
    52  //         force-command /bin/sleep
    53  //         source-address 192.168.1.0/24
    54  // Extensions:
    55  //         permit-X11-forwarding
    56  //         permit-agent-forwarding
    57  //         permit-port-forwarding
    58  //         permit-pty
    59  //         permit-user-rc
    60  const exampleSSHCertWithOptions = `ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgDyysCJY0XrO1n03EeRRoITnTPdjENFmWDs9X58PP3VUAAAADAQABAAABAQDACh1rt2DXfV3hk6fszSQcQ/rueMId0kVD9U7nl8cfEnFxqOCrNT92g4laQIGl2mn8lsGZfTLg8ksHq3gkvgO3oo/0wHy4v32JeBOHTsN5AL4gfHNEhWeWb50ev47hnTsRIt9P4dxogeUo/hTu7j9+s9lLpEQXCvq6xocXQt0j8MV9qZBBXFLXVT3cWIkSqOdwt/5ZBg+1GSrc7WfCXVWgTk4a20uPMuJPxU4RQwZW6X3+O8Pqo8C3cW0OzZRFP6gUYUKUsTI5WntlS+LAxgw1mZNsozFGdbiOPRnEryE3SRldh9vjDR3tin1fGpA5P7+CEB/bqaXtG3V+F2OkqaMNAAAAAAAAAAAAAAABAAAACHRlc3RjZXJ0AAAAAAAAAAAAAAAA//////////8AAABLAAAADWZvcmNlLWNvbW1hbmQAAAAOAAAACi9iaW4vc2xlZXAAAAAOc291cmNlLWFkZHJlc3MAAAASAAAADjE5Mi4xNjguMS4wLzI0AAAAggAAABVwZXJtaXQtWDExLWZvcndhcmRpbmcAAAAAAAAAF3Blcm1pdC1hZ2VudC1mb3J3YXJkaW5nAAAAAAAAABZwZXJtaXQtcG9ydC1mb3J3YXJkaW5nAAAAAAAAAApwZXJtaXQtcHR5AAAAAAAAAA5wZXJtaXQtdXNlci1yYwAAAAAAAAAAAAABFwAAAAdzc2gtcnNhAAAAAwEAAQAAAQEAwU+c5ui5A8+J/CFpjW8wCa52bEODA808WWQDCSuTG/eMXNf59v9Y8Pk0F1E9dGCosSNyVcB/hacUrc6He+i97+HJCyKavBsE6GDxrjRyxYqAlfcOXi/IVmaUGiO8OQ39d4GHrjToInKvExSUeleQyH4Y4/e27T/pILAqPFL3fyrvMLT5qU9QyIt6zIpa7GBP5+urouNavMprV3zsfIqNBbWypinOQAw823a5wN+zwXnhZrgQiHZ/USG09Y6k98y1dTVz8YHlQVR4D3lpTAsKDKJ5hCH9WU4fdf+lU8OyNGaJ/vz0XNqxcToe1l4numLTnaoSuH89pHryjqurB7lJKwAAAQ8AAAAHc3NoLXJzYQAAAQCaHvUIoPL1zWUHIXLvu96/HU1s/i4CAW2IIEuGgxCUCiFj6vyTyYtgxQxcmbfZf6eaITlS6XJZa7Qq4iaFZh75C1DXTX8labXhRSD4E2t//AIP9MC1rtQC5xo6FmbQ+BoKcDskr+mNACcbRSxs3IL3bwCfWDnIw2WbVox9ZdcthJKk4UoCW4ix4QwdHw7zlddlz++fGEEVhmTbll1SUkycGApPFBsAYRTMupUJcYPIeReBI/m8XfkoMk99bV8ZJQTAd7OekHY2/48Ff53jLmyDjP7kNw1F8OaPtkFs6dGJXta4krmaekPy87j+35In5hFj7yoOqvSbmYUkeX70/GGQ`
    61  
    62  func TestParseCertWithOptions(t *testing.T) {
    63  	opts := map[string]string{
    64  		"source-address": "192.168.1.0/24",
    65  		"force-command":  "/bin/sleep",
    66  	}
    67  	exts := map[string]string{
    68  		"permit-X11-forwarding":   "",
    69  		"permit-agent-forwarding": "",
    70  		"permit-port-forwarding":  "",
    71  		"permit-pty":              "",
    72  		"permit-user-rc":          "",
    73  	}
    74  	authKeyBytes := []byte(exampleSSHCertWithOptions)
    75  
    76  	key, _, _, rest, err := ParseAuthorizedKey(authKeyBytes)
    77  	if err != nil {
    78  		t.Fatalf("ParseAuthorizedKey: %v", err)
    79  	}
    80  	if len(rest) > 0 {
    81  		t.Errorf("rest: got %q, want empty", rest)
    82  	}
    83  	cert, ok := key.(*Certificate)
    84  	if !ok {
    85  		t.Fatalf("got %v (%T), want *Certificate", key, key)
    86  	}
    87  	if !reflect.DeepEqual(cert.CriticalOptions, opts) {
    88  		t.Errorf("unexpected critical options - got %v, want %v", cert.CriticalOptions, opts)
    89  	}
    90  	if !reflect.DeepEqual(cert.Extensions, exts) {
    91  		t.Errorf("unexpected Extensions - got %v, want %v", cert.Extensions, exts)
    92  	}
    93  	marshaled := MarshalAuthorizedKey(key)
    94  	// Before comparison, remove the trailing newline that
    95  	// MarshalAuthorizedKey adds.
    96  	marshaled = marshaled[:len(marshaled)-1]
    97  	if !bytes.Equal(authKeyBytes, marshaled) {
    98  		t.Errorf("marshaled certificate does not match original: got %q, want %q", marshaled, authKeyBytes)
    99  	}
   100  }
   101  
   102  func TestValidateCert(t *testing.T) {
   103  	key, _, _, _, err := ParseAuthorizedKey([]byte(exampleSSHCert))
   104  	if err != nil {
   105  		t.Fatalf("ParseAuthorizedKey: %v", err)
   106  	}
   107  	validCert, ok := key.(*Certificate)
   108  	if !ok {
   109  		t.Fatalf("got %v (%T), want *Certificate", key, key)
   110  	}
   111  	checker := CertChecker{}
   112  	checker.IsUserAuthority = func(k PublicKey) bool {
   113  		return bytes.Equal(k.Marshal(), validCert.SignatureKey.Marshal())
   114  	}
   115  
   116  	if err := checker.CheckCert("user", validCert); err != nil {
   117  		t.Errorf("Unable to validate certificate: %v", err)
   118  	}
   119  	invalidCert := &Certificate{
   120  		Key:          testPublicKeys["rsa"],
   121  		SignatureKey: testPublicKeys["ecdsa"],
   122  		ValidBefore:  CertTimeInfinity,
   123  		Signature:    &Signature{},
   124  	}
   125  	if err := checker.CheckCert("user", invalidCert); err == nil {
   126  		t.Error("Invalid cert signature passed validation")
   127  	}
   128  }
   129  
   130  func TestValidateCertTime(t *testing.T) {
   131  	cert := Certificate{
   132  		ValidPrincipals: []string{"user"},
   133  		Key:             testPublicKeys["rsa"],
   134  		ValidAfter:      50,
   135  		ValidBefore:     100,
   136  	}
   137  
   138  	cert.SignCert(rand.Reader, testSigners["ecdsa"])
   139  
   140  	for ts, ok := range map[int64]bool{
   141  		25:  false,
   142  		50:  true,
   143  		99:  true,
   144  		100: false,
   145  		125: false,
   146  	} {
   147  		checker := CertChecker{
   148  			Clock: func() time.Time { return time.Unix(ts, 0) },
   149  		}
   150  		checker.IsUserAuthority = func(k PublicKey) bool {
   151  			return bytes.Equal(k.Marshal(),
   152  				testPublicKeys["ecdsa"].Marshal())
   153  		}
   154  
   155  		if v := checker.CheckCert("user", &cert); (v == nil) != ok {
   156  			t.Errorf("Authenticate(%d): %v", ts, v)
   157  		}
   158  	}
   159  }
   160  
   161  // TODO(hanwen): tests for
   162  //
   163  // host keys:
   164  // * fallbacks
   165  
   166  func TestHostKeyCert(t *testing.T) {
   167  	cert := &Certificate{
   168  		ValidPrincipals: []string{"hostname", "hostname.domain", "otherhost"},
   169  		Key:             testPublicKeys["rsa"],
   170  		ValidBefore:     CertTimeInfinity,
   171  		CertType:        HostCert,
   172  	}
   173  	cert.SignCert(rand.Reader, testSigners["ecdsa"])
   174  
   175  	checker := &CertChecker{
   176  		IsHostAuthority: func(p PublicKey, addr string) bool {
   177  			return addr == "hostname:22" && bytes.Equal(testPublicKeys["ecdsa"].Marshal(), p.Marshal())
   178  		},
   179  	}
   180  
   181  	certSigner, err := NewCertSigner(cert, testSigners["rsa"])
   182  	if err != nil {
   183  		t.Errorf("NewCertSigner: %v", err)
   184  	}
   185  
   186  	for _, test := range []struct {
   187  		addr    string
   188  		succeed bool
   189  	}{
   190  		{addr: "hostname:22", succeed: true},
   191  		{addr: "otherhost:22", succeed: false}, // The certificate is valid for 'otherhost' as hostname, but we only recognize the authority of the signer for the address 'hostname:22'
   192  		{addr: "lasthost:22", succeed: false},
   193  	} {
   194  		c1, c2, err := netPipe()
   195  		if err != nil {
   196  			t.Fatalf("netPipe: %v", err)
   197  		}
   198  		defer c1.Close()
   199  		defer c2.Close()
   200  
   201  		errc := make(chan error)
   202  
   203  		go func() {
   204  			conf := ServerConfig{
   205  				NoClientAuth: true,
   206  			}
   207  			conf.AddHostKey(certSigner)
   208  			_, _, _, err := NewServerConn(c1, &conf)
   209  			errc <- err
   210  		}()
   211  
   212  		config := &ClientConfig{
   213  			User:            "user",
   214  			HostKeyCallback: checker.CheckHostKey,
   215  		}
   216  		_, _, _, err = NewClientConn(c2, test.addr, config)
   217  
   218  		if (err == nil) != test.succeed {
   219  			t.Fatalf("NewClientConn(%q): %v", test.addr, err)
   220  		}
   221  
   222  		err = <-errc
   223  		if (err == nil) != test.succeed {
   224  			t.Fatalf("NewServerConn(%q): %v", test.addr, err)
   225  		}
   226  	}
   227  }
   228  
   229  type legacyRSASigner struct {
   230  	Signer
   231  }
   232  
   233  func (s *legacyRSASigner) Sign(rand io.Reader, data []byte) (*Signature, error) {
   234  	v, ok := s.Signer.(AlgorithmSigner)
   235  	if !ok {
   236  		return nil, fmt.Errorf("invalid signer")
   237  	}
   238  	return v.SignWithAlgorithm(rand, data, SigAlgoRSA)
   239  }
   240  
   241  func TestCertTypes(t *testing.T) {
   242  	var testVars = []struct {
   243  		name   string
   244  		signer Signer
   245  		algo   string
   246  	}{
   247  		{CertAlgoECDSA256v01, testSigners["ecdsap256"], ""},
   248  		{CertAlgoECDSA384v01, testSigners["ecdsap384"], ""},
   249  		{CertAlgoECDSA521v01, testSigners["ecdsap521"], ""},
   250  		{CertAlgoED25519v01, testSigners["ed25519"], ""},
   251  		{CertAlgoRSAv01, testSigners["rsa"], SigAlgoRSASHA2512},
   252  		{CertAlgoRSAv01, &legacyRSASigner{testSigners["rsa"]}, SigAlgoRSA},
   253  		{CertAlgoRSAv01, testSigners["rsa-sha2-256"], SigAlgoRSASHA2512},
   254  		{CertAlgoRSAv01, testSigners["rsa-sha2-512"], SigAlgoRSASHA2512},
   255  		{CertAlgoDSAv01, testSigners["dsa"], ""},
   256  	}
   257  
   258  	k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
   259  	if err != nil {
   260  		t.Fatalf("error generating host key: %v", err)
   261  	}
   262  
   263  	signer, err := NewSignerFromKey(k)
   264  	if err != nil {
   265  		t.Fatalf("error generating signer for ssh listener: %v", err)
   266  	}
   267  
   268  	conf := &ServerConfig{
   269  		PublicKeyCallback: func(c ConnMetadata, k PublicKey) (*Permissions, error) {
   270  			return new(Permissions), nil
   271  		},
   272  	}
   273  	conf.AddHostKey(signer)
   274  
   275  	for _, m := range testVars {
   276  		t.Run(m.name, func(t *testing.T) {
   277  
   278  			c1, c2, err := netPipe()
   279  			if err != nil {
   280  				t.Fatalf("netPipe: %v", err)
   281  			}
   282  			defer c1.Close()
   283  			defer c2.Close()
   284  
   285  			go NewServerConn(c1, conf)
   286  
   287  			priv := m.signer
   288  			if err != nil {
   289  				t.Fatalf("error generating ssh pubkey: %v", err)
   290  			}
   291  
   292  			cert := &Certificate{
   293  				CertType: UserCert,
   294  				Key:      priv.PublicKey(),
   295  			}
   296  			cert.SignCert(rand.Reader, priv)
   297  
   298  			certSigner, err := NewCertSigner(cert, priv)
   299  			if err != nil {
   300  				t.Fatalf("error generating cert signer: %v", err)
   301  			}
   302  
   303  			if m.algo != "" && cert.Signature.Format != m.algo {
   304  				t.Errorf("expected %q signature format, got %q", m.algo, cert.Signature.Format)
   305  			}
   306  
   307  			config := &ClientConfig{
   308  				User:            "user",
   309  				HostKeyCallback: func(h string, r net.Addr, k PublicKey) error { return nil },
   310  				Auth:            []AuthMethod{PublicKeys(certSigner)},
   311  			}
   312  
   313  			_, _, _, err = NewClientConn(c2, "", config)
   314  			if err != nil {
   315  				t.Fatalf("error connecting: %v", err)
   316  			}
   317  		})
   318  	}
   319  }