...

Source file src/gopkg.in/square/go-jose.v2/asymmetric_test.go

Documentation: gopkg.in/square/go-jose.v2

     1  /*-
     2   * Copyright 2014 Square Inc.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package jose
    18  
    19  import (
    20  	"crypto/ecdsa"
    21  	"crypto/elliptic"
    22  	"crypto/rand"
    23  	"crypto/rsa"
    24  	"errors"
    25  	"io"
    26  	"testing"
    27  )
    28  
    29  func TestEd25519(t *testing.T) {
    30  	_, err := newEd25519Signer("XYZ", nil)
    31  	if err != ErrUnsupportedAlgorithm {
    32  		t.Error("should return error on invalid algorithm")
    33  	}
    34  
    35  	enc := new(edEncrypterVerifier)
    36  	enc.publicKey = ed25519PublicKey
    37  	err = enc.verifyPayload([]byte{}, []byte{}, "XYZ")
    38  	if err != ErrUnsupportedAlgorithm {
    39  		t.Error("should return error on invalid algorithm")
    40  	}
    41  
    42  	dec := new(edDecrypterSigner)
    43  	dec.privateKey = ed25519PrivateKey
    44  	_, err = dec.signPayload([]byte{}, "XYZ")
    45  	if err != ErrUnsupportedAlgorithm {
    46  		t.Error("should return error on invalid algorithm")
    47  	}
    48  
    49  	sig, err := dec.signPayload([]byte("This is a test"), "EdDSA")
    50  	if err != nil {
    51  		t.Error("should not error trying to sign payload")
    52  	}
    53  	if sig.Signature == nil {
    54  		t.Error("Check the signature")
    55  	}
    56  	err = enc.verifyPayload([]byte("This is a test"), sig.Signature, "EdDSA")
    57  	if err != nil {
    58  		t.Error("should not error trying to verify payload")
    59  	}
    60  
    61  	err = enc.verifyPayload([]byte("This is test number 2"), sig.Signature, "EdDSA")
    62  	if err == nil {
    63  		t.Error("should not error trying to verify payload")
    64  	}
    65  }
    66  
    67  func TestInvalidAlgorithmsRSA(t *testing.T) {
    68  	_, err := newRSARecipient("XYZ", nil)
    69  	if err != ErrUnsupportedAlgorithm {
    70  		t.Error("should return error on invalid algorithm")
    71  	}
    72  
    73  	_, err = newRSASigner("XYZ", nil)
    74  	if err != ErrUnsupportedAlgorithm {
    75  		t.Error("should return error on invalid algorithm")
    76  	}
    77  
    78  	enc := new(rsaEncrypterVerifier)
    79  	enc.publicKey = &rsaTestKey.PublicKey
    80  	_, err = enc.encryptKey([]byte{}, "XYZ")
    81  	if err != ErrUnsupportedAlgorithm {
    82  		t.Error("should return error on invalid algorithm")
    83  	}
    84  
    85  	err = enc.verifyPayload([]byte{}, []byte{}, "XYZ")
    86  	if err != ErrUnsupportedAlgorithm {
    87  		t.Error("should return error on invalid algorithm")
    88  	}
    89  
    90  	dec := new(rsaDecrypterSigner)
    91  	dec.privateKey = rsaTestKey
    92  	_, err = dec.decrypt(make([]byte, 256), "XYZ", randomKeyGenerator{size: 16})
    93  	if err != ErrUnsupportedAlgorithm {
    94  		t.Error("should return error on invalid algorithm")
    95  	}
    96  
    97  	_, err = dec.signPayload([]byte{}, "XYZ")
    98  	if err != ErrUnsupportedAlgorithm {
    99  		t.Error("should return error on invalid algorithm")
   100  	}
   101  }
   102  
   103  type failingKeyGenerator struct{}
   104  
   105  func (ctx failingKeyGenerator) keySize() int {
   106  	return 0
   107  }
   108  
   109  func (ctx failingKeyGenerator) genKey() ([]byte, rawHeader, error) {
   110  	return nil, rawHeader{}, errors.New("failed to generate key")
   111  }
   112  
   113  func TestPKCSKeyGeneratorFailure(t *testing.T) {
   114  	dec := new(rsaDecrypterSigner)
   115  	dec.privateKey = rsaTestKey
   116  	generator := failingKeyGenerator{}
   117  	_, err := dec.decrypt(make([]byte, 256), RSA1_5, generator)
   118  	if err != ErrCryptoFailure {
   119  		t.Error("should return error on invalid algorithm")
   120  	}
   121  }
   122  
   123  func TestInvalidAlgorithmsEC(t *testing.T) {
   124  	_, err := newECDHRecipient("XYZ", nil)
   125  	if err != ErrUnsupportedAlgorithm {
   126  		t.Error("should return error on invalid algorithm")
   127  	}
   128  
   129  	_, err = newECDSASigner("XYZ", nil)
   130  	if err != ErrUnsupportedAlgorithm {
   131  		t.Error("should return error on invalid algorithm")
   132  	}
   133  
   134  	enc := new(ecEncrypterVerifier)
   135  	enc.publicKey = &ecTestKey256.PublicKey
   136  	_, err = enc.encryptKey([]byte{}, "XYZ")
   137  	if err != ErrUnsupportedAlgorithm {
   138  		t.Error("should return error on invalid algorithm")
   139  	}
   140  }
   141  
   142  func TestInvalidECKeyGen(t *testing.T) {
   143  	gen := ecKeyGenerator{
   144  		size:      16,
   145  		algID:     "A128GCM",
   146  		publicKey: &ecTestKey256.PublicKey,
   147  	}
   148  
   149  	if gen.keySize() != 16 {
   150  		t.Error("ec key generator reported incorrect key size")
   151  	}
   152  
   153  	_, _, err := gen.genKey()
   154  	if err != nil {
   155  		t.Error("ec key generator failed to generate key", err)
   156  	}
   157  }
   158  
   159  func TestInvalidECDecrypt(t *testing.T) {
   160  	dec := ecDecrypterSigner{
   161  		privateKey: ecTestKey256,
   162  	}
   163  
   164  	generator := randomKeyGenerator{size: 16}
   165  
   166  	// Missing epk header
   167  	headers := rawHeader{}
   168  	headers.set(headerAlgorithm, ECDH_ES)
   169  
   170  	_, err := dec.decryptKey(headers, nil, generator)
   171  	if err == nil {
   172  		t.Error("ec decrypter accepted object with missing epk header")
   173  	}
   174  
   175  	// Invalid epk header
   176  	headers.set(headerEPK, &JSONWebKey{})
   177  
   178  	_, err = dec.decryptKey(headers, nil, generator)
   179  	if err == nil {
   180  		t.Error("ec decrypter accepted object with invalid epk header")
   181  	}
   182  }
   183  
   184  func TestDecryptWithIncorrectSize(t *testing.T) {
   185  	priv, err := rsa.GenerateKey(rand.Reader, 2048)
   186  	if err != nil {
   187  		t.Error(err)
   188  		return
   189  	}
   190  
   191  	dec := new(rsaDecrypterSigner)
   192  	dec.privateKey = priv
   193  	aes := newAESGCM(16)
   194  
   195  	keygen := randomKeyGenerator{
   196  		size: aes.keySize(),
   197  	}
   198  
   199  	payload := make([]byte, 254)
   200  	_, err = dec.decrypt(payload, RSA1_5, keygen)
   201  	if err == nil {
   202  		t.Error("Invalid payload size should return error")
   203  	}
   204  
   205  	payload = make([]byte, 257)
   206  	_, err = dec.decrypt(payload, RSA1_5, keygen)
   207  	if err == nil {
   208  		t.Error("Invalid payload size should return error")
   209  	}
   210  }
   211  
   212  func TestPKCSDecryptNeverFails(t *testing.T) {
   213  	// We don't want RSA-PKCS1 v1.5 decryption to ever fail, in order to prevent
   214  	// side-channel timing attacks (Bleichenbacher attack in particular).
   215  	priv, err := rsa.GenerateKey(rand.Reader, 2048)
   216  	if err != nil {
   217  		t.Error(err)
   218  		return
   219  	}
   220  
   221  	dec := new(rsaDecrypterSigner)
   222  	dec.privateKey = priv
   223  	aes := newAESGCM(16)
   224  
   225  	keygen := randomKeyGenerator{
   226  		size: aes.keySize(),
   227  	}
   228  
   229  	for i := 1; i < 50; i++ {
   230  		payload := make([]byte, 256)
   231  		_, err := io.ReadFull(rand.Reader, payload)
   232  		if err != nil {
   233  			t.Error("Unable to get random data:", err)
   234  			return
   235  		}
   236  		_, err = dec.decrypt(payload, RSA1_5, keygen)
   237  		if err != nil {
   238  			t.Error("PKCS1v1.5 decrypt should never fail:", err)
   239  			return
   240  		}
   241  	}
   242  }
   243  
   244  func BenchmarkPKCSDecryptWithValidPayloads(b *testing.B) {
   245  	priv, err := rsa.GenerateKey(rand.Reader, 2048)
   246  	if err != nil {
   247  		panic(err)
   248  	}
   249  
   250  	enc := new(rsaEncrypterVerifier)
   251  	enc.publicKey = &priv.PublicKey
   252  	dec := new(rsaDecrypterSigner)
   253  	dec.privateKey = priv
   254  	aes := newAESGCM(32)
   255  
   256  	b.StopTimer()
   257  	b.ResetTimer()
   258  	for i := 0; i < b.N; i++ {
   259  		plaintext := make([]byte, 32)
   260  		_, err = io.ReadFull(rand.Reader, plaintext)
   261  		if err != nil {
   262  			panic(err)
   263  		}
   264  
   265  		ciphertext, err := enc.encrypt(plaintext, RSA1_5)
   266  		if err != nil {
   267  			panic(err)
   268  		}
   269  
   270  		keygen := randomKeyGenerator{
   271  			size: aes.keySize(),
   272  		}
   273  
   274  		b.StartTimer()
   275  		_, err = dec.decrypt(ciphertext, RSA1_5, keygen)
   276  		b.StopTimer()
   277  		if err != nil {
   278  			panic(err)
   279  		}
   280  	}
   281  }
   282  
   283  func BenchmarkPKCSDecryptWithInvalidPayloads(b *testing.B) {
   284  	priv, err := rsa.GenerateKey(rand.Reader, 2048)
   285  	if err != nil {
   286  		panic(err)
   287  	}
   288  
   289  	enc := new(rsaEncrypterVerifier)
   290  	enc.publicKey = &priv.PublicKey
   291  	dec := new(rsaDecrypterSigner)
   292  	dec.privateKey = priv
   293  	aes := newAESGCM(16)
   294  
   295  	keygen := randomKeyGenerator{
   296  		size: aes.keySize(),
   297  	}
   298  
   299  	b.StopTimer()
   300  	b.ResetTimer()
   301  	for i := 0; i < b.N; i++ {
   302  		plaintext := make([]byte, 16)
   303  		_, err = io.ReadFull(rand.Reader, plaintext)
   304  		if err != nil {
   305  			panic(err)
   306  		}
   307  
   308  		ciphertext, err := enc.encrypt(plaintext, RSA1_5)
   309  		if err != nil {
   310  			panic(err)
   311  		}
   312  
   313  		// Do some simple scrambling
   314  		ciphertext[128] ^= 0xFF
   315  
   316  		b.StartTimer()
   317  		_, err = dec.decrypt(ciphertext, RSA1_5, keygen)
   318  		b.StopTimer()
   319  		if err != nil {
   320  			panic(err)
   321  		}
   322  	}
   323  }
   324  
   325  func TestInvalidEllipticCurve(t *testing.T) {
   326  	signer256 := ecDecrypterSigner{privateKey: ecTestKey256}
   327  	signer384 := ecDecrypterSigner{privateKey: ecTestKey384}
   328  	signer521 := ecDecrypterSigner{privateKey: ecTestKey521}
   329  
   330  	_, err := signer256.signPayload([]byte{}, ES384)
   331  	if err == nil {
   332  		t.Error("should not generate ES384 signature with P-256 key")
   333  	}
   334  	_, err = signer256.signPayload([]byte{}, ES512)
   335  	if err == nil {
   336  		t.Error("should not generate ES512 signature with P-256 key")
   337  	}
   338  	_, err = signer384.signPayload([]byte{}, ES256)
   339  	if err == nil {
   340  		t.Error("should not generate ES256 signature with P-384 key")
   341  	}
   342  	_, err = signer384.signPayload([]byte{}, ES512)
   343  	if err == nil {
   344  		t.Error("should not generate ES512 signature with P-384 key")
   345  	}
   346  	_, err = signer521.signPayload([]byte{}, ES256)
   347  	if err == nil {
   348  		t.Error("should not generate ES256 signature with P-521 key")
   349  	}
   350  	_, err = signer521.signPayload([]byte{}, ES384)
   351  	if err == nil {
   352  		t.Error("should not generate ES384 signature with P-521 key")
   353  	}
   354  }
   355  
   356  func estInvalidECPublicKey(t *testing.T) {
   357  	// Invalid key
   358  	invalid := &ecdsa.PrivateKey{
   359  		PublicKey: ecdsa.PublicKey{
   360  			Curve: elliptic.P256(),
   361  			X:     fromBase64Int("MTEx"),
   362  			Y:     fromBase64Int("MTEx"),
   363  		},
   364  		D: fromBase64Int("0_NxaRPUMQoAJt50Gz8YiTr8gRTwyEaCumd-MToTmIo"),
   365  	}
   366  
   367  	headers := rawHeader{}
   368  	headers.set(headerAlgorithm, ECDH_ES)
   369  	headers.set(headerEPK, &JSONWebKey{
   370  		Key: &invalid.PublicKey,
   371  	})
   372  
   373  	dec := ecDecrypterSigner{
   374  		privateKey: ecTestKey256,
   375  	}
   376  
   377  	_, err := dec.decryptKey(headers, nil, randomKeyGenerator{size: 16})
   378  	if err == nil {
   379  		t.Fatal("decrypter accepted JWS with invalid ECDH public key")
   380  	}
   381  }
   382  
   383  func TestInvalidAlgorithmEC(t *testing.T) {
   384  	err := ecEncrypterVerifier{publicKey: &ecTestKey256.PublicKey}.verifyPayload([]byte{}, []byte{}, "XYZ")
   385  	if err != ErrUnsupportedAlgorithm {
   386  		t.Fatal("should not accept invalid/unsupported algorithm")
   387  	}
   388  }
   389  

View as plain text