github.com/glycerine/xcryptossh@v7.0.4+incompatible/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  	"context"
    10  	"crypto/rand"
    11  	"reflect"
    12  	"testing"
    13  	"time"
    14  )
    15  
    16  // Cert generated by ssh-keygen 6.0p1 Debian-4.
    17  // % ssh-keygen -s ca-key -I test user-key
    18  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=`
    19  
    20  func TestParseCert(t *testing.T) {
    21  	defer xtestend(xtestbegin(t))
    22  
    23  	authKeyBytes := []byte(exampleSSHCert)
    24  
    25  	key, _, _, rest, err := ParseAuthorizedKey(authKeyBytes)
    26  	if err != nil {
    27  		t.Fatalf("ParseAuthorizedKey: %v", err)
    28  	}
    29  	if len(rest) > 0 {
    30  		t.Errorf("rest: got %q, want empty", rest)
    31  	}
    32  
    33  	if _, ok := key.(*Certificate); !ok {
    34  		t.Fatalf("got %v (%T), want *Certificate", key, key)
    35  	}
    36  
    37  	marshaled := MarshalAuthorizedKey(key)
    38  	// Before comparison, remove the trailing newline that
    39  	// MarshalAuthorizedKey adds.
    40  	marshaled = marshaled[:len(marshaled)-1]
    41  	if !bytes.Equal(authKeyBytes, marshaled) {
    42  		t.Errorf("marshaled certificate does not match original: got %q, want %q", marshaled, authKeyBytes)
    43  	}
    44  }
    45  
    46  // Cert generated by ssh-keygen OpenSSH_6.8p1 OS X 10.10.3
    47  // % ssh-keygen -s ca -I testcert -O source-address=192.168.1.0/24 -O force-command=/bin/sleep user.pub
    48  // user.pub key: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDACh1rt2DXfV3hk6fszSQcQ/rueMId0kVD9U7nl8cfEnFxqOCrNT92g4laQIGl2mn8lsGZfTLg8ksHq3gkvgO3oo/0wHy4v32JeBOHTsN5AL4gfHNEhWeWb50ev47hnTsRIt9P4dxogeUo/hTu7j9+s9lLpEQXCvq6xocXQt0j8MV9qZBBXFLXVT3cWIkSqOdwt/5ZBg+1GSrc7WfCXVWgTk4a20uPMuJPxU4RQwZW6X3+O8Pqo8C3cW0OzZRFP6gUYUKUsTI5WntlS+LAxgw1mZNsozFGdbiOPRnEryE3SRldh9vjDR3tin1fGpA5P7+CEB/bqaXtG3V+F2OkqaMN
    49  // Critical Options:
    50  //         force-command /bin/sleep
    51  //         source-address 192.168.1.0/24
    52  // Extensions:
    53  //         permit-X11-forwarding
    54  //         permit-agent-forwarding
    55  //         permit-port-forwarding
    56  //         permit-pty
    57  //         permit-user-rc
    58  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`
    59  
    60  func TestParseCertWithOptions(t *testing.T) {
    61  	defer xtestend(xtestbegin(t))
    62  
    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  	defer xtestend(xtestbegin(t))
   104  
   105  	key, _, _, _, err := ParseAuthorizedKey([]byte(exampleSSHCert))
   106  	if err != nil {
   107  		t.Fatalf("ParseAuthorizedKey: %v", err)
   108  	}
   109  	validCert, ok := key.(*Certificate)
   110  	if !ok {
   111  		t.Fatalf("got %v (%T), want *Certificate", key, key)
   112  	}
   113  	checker := CertChecker{}
   114  	checker.IsUserAuthority = func(k PublicKey) bool {
   115  		return bytes.Equal(k.Marshal(), validCert.SignatureKey.Marshal())
   116  	}
   117  
   118  	if err := checker.CheckCert("user", validCert); err != nil {
   119  		t.Errorf("Unable to validate certificate: %v", err)
   120  	}
   121  	invalidCert := &Certificate{
   122  		Key:          testPublicKeys["rsa"],
   123  		SignatureKey: testPublicKeys["ecdsa"],
   124  		ValidBefore:  CertTimeInfinity,
   125  		Signature:    &Signature{},
   126  	}
   127  	if err := checker.CheckCert("user", invalidCert); err == nil {
   128  		t.Error("Invalid cert signature passed validation")
   129  	}
   130  }
   131  
   132  func TestValidateCertTime(t *testing.T) {
   133  	defer xtestend(xtestbegin(t))
   134  
   135  	cert := Certificate{
   136  		ValidPrincipals: []string{"user"},
   137  		Key:             testPublicKeys["rsa"],
   138  		ValidAfter:      50,
   139  		ValidBefore:     100,
   140  	}
   141  
   142  	cert.SignCert(rand.Reader, testSigners["ecdsa"])
   143  
   144  	for ts, ok := range map[int64]bool{
   145  		25:  false,
   146  		50:  true,
   147  		99:  true,
   148  		100: false,
   149  		125: false,
   150  	} {
   151  		checker := CertChecker{
   152  			Clock: func() time.Time { return time.Unix(ts, 0) },
   153  		}
   154  		checker.IsUserAuthority = func(k PublicKey) bool {
   155  			return bytes.Equal(k.Marshal(),
   156  				testPublicKeys["ecdsa"].Marshal())
   157  		}
   158  
   159  		if v := checker.CheckCert("user", &cert); (v == nil) != ok {
   160  			t.Errorf("Authenticate(%d): %v", ts, v)
   161  		}
   162  	}
   163  }
   164  
   165  // TODO(hanwen): tests for
   166  //
   167  // host keys:
   168  // * fallbacks
   169  
   170  func TestHostKeyCert(t *testing.T) {
   171  	defer xtestend(xtestbegin(t))
   172  
   173  	cert := &Certificate{
   174  		ValidPrincipals: []string{"hostname", "hostname.domain", "otherhost"},
   175  		Key:             testPublicKeys["rsa"],
   176  		ValidBefore:     CertTimeInfinity,
   177  		CertType:        HostCert,
   178  	}
   179  	cert.SignCert(rand.Reader, testSigners["ecdsa"])
   180  
   181  	checker := &CertChecker{
   182  		IsHostAuthority: func(p PublicKey, addr string) bool {
   183  			return addr == "hostname:22" && bytes.Equal(testPublicKeys["ecdsa"].Marshal(), p.Marshal())
   184  		},
   185  	}
   186  
   187  	halt := NewHalter()
   188  	defer halt.RequestStop()
   189  	certSigner, err := NewCertSigner(cert, testSigners["rsa"])
   190  	if err != nil {
   191  		t.Errorf("NewCertSigner: %v", err)
   192  	}
   193  
   194  	for _, test := range []struct {
   195  		addr    string
   196  		succeed bool
   197  	}{
   198  		{addr: "hostname:22", succeed: true},
   199  		{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'
   200  		{addr: "lasthost:22", succeed: false},
   201  	} {
   202  		c1, c2, err := netPipe()
   203  		if err != nil {
   204  			t.Fatalf("netPipe: %v", err)
   205  		}
   206  		defer c1.Close()
   207  		defer c2.Close()
   208  
   209  		errc := make(chan error)
   210  		ctx := context.Background()
   211  		go func() {
   212  			conf := ServerConfig{
   213  				NoClientAuth: true,
   214  				Config: Config{
   215  					Halt: halt,
   216  				},
   217  			}
   218  			conf.AddHostKey(certSigner)
   219  			_, _, _, err := NewServerConn(ctx, c1, &conf)
   220  			errc <- err
   221  		}()
   222  
   223  		config := &ClientConfig{
   224  			User:            "user",
   225  			HostKeyCallback: checker.CheckHostKey,
   226  			Config: Config{
   227  				Halt: halt,
   228  			},
   229  		}
   230  		_, _, _, err = NewClientConn(ctx, c2, test.addr, config)
   231  		defer config.Halt.RequestStop()
   232  
   233  		if (err == nil) != test.succeed {
   234  			t.Fatalf("NewClientConn(%q): %v", test.addr, err)
   235  		}
   236  
   237  		err = <-errc
   238  		if (err == nil) != test.succeed {
   239  			t.Fatalf("NewServerConn(%q): %v", test.addr, err)
   240  		}
   241  	}
   242  }