Exemple #1
0
func (node *nodeImpl) loadEnrollmentCertificate() error {
	node.log.Debug("Loading enrollment certificate...")

	cert, der, err := node.ks.loadCertX509AndDer(node.conf.getEnrollmentCertFilename())
	if err != nil {
		node.log.Error("Failed parsing enrollment certificate [%s].", err.Error())

		return err
	}
	node.enrollCert = cert

	// TODO: move this to retrieve
	pk := node.enrollCert.PublicKey.(*ecdsa.PublicKey)
	err = utils.VerifySignCapability(node.enrollPrivKey, pk)
	if err != nil {
		node.log.Error("Failed checking enrollment certificate against enrollment key [%s].", err.Error())

		return err
	}

	// Set node ID
	node.id = utils.Hash(der)
	node.log.Debug("Setting id to [%s].", utils.EncodeBase64(node.id))

	// Set eCertHash
	node.enrollCertHash = utils.Hash(der)
	node.log.Debug("Setting enrollCertHash to [%s].", utils.EncodeBase64(node.enrollCertHash))

	return nil
}
Exemple #2
0
func (node *nodeImpl) loadEnrollmentCertificate() error {
	node.log.Debug("Loading enrollment certificate at [%s]...", node.conf.getEnrollmentCertPath())

	pemEnrollCert, err := ioutil.ReadFile(node.conf.getEnrollmentCertPath())
	if err != nil {
		node.log.Error("Failed loading enrollment certificate [%s].", err.Error())

		return err
	}

	enrollCert, rawEnrollCert, err := utils.PEMtoCertificateAndDER(pemEnrollCert)
	if err != nil {
		node.log.Error("Failed parsing enrollment certificate [%s].", err.Error())

		return err
	}
	node.enrollCert = enrollCert

	pk := node.enrollCert.PublicKey.(*ecdsa.PublicKey)
	err = utils.VerifySignCapability(node.enrollPrivKey, pk)
	if err != nil {
		node.log.Error("Failed checking enrollment certificate against enrollment key [%s].", err.Error())

		return err
	}

	// Set node ID
	node.id = utils.Hash(rawEnrollCert)
	node.log.Debug("Setting id to [%s].", utils.EncodeBase64(node.id))

	return nil
}
Exemple #3
0
func (node *nodeImpl) getTLSCertificateFromTLSCA(id, affiliation string) (interface{}, []byte, error) {
	node.log.Info("getTLSCertificate...")

	priv, err := utils.NewECDSAKey()

	if err != nil {
		node.log.Error("Failed generating key: %s", err)

		return nil, nil, err
	}

	uuid, err := util.GenerateUUID()
	if err != nil {
		node.log.Error("Failed generating uuid: %s", err)

		return nil, nil, err
	}

	// Prepare the request
	pubraw, _ := x509.MarshalPKIXPublicKey(&priv.PublicKey)
	now := time.Now()
	timestamp := google_protobuf.Timestamp{int64(now.Second()), int32(now.Nanosecond())}

	req := &obcca.TLSCertCreateReq{
		&timestamp,
		&obcca.Identity{Id: id + "-" + uuid},
		&obcca.Password{Pw: ""},
		&obcca.PublicKey{
			Type: obcca.CryptoType_ECDSA,
			Key:  pubraw,
		}, nil}
	rawreq, _ := proto.Marshal(req)
	r, s, err := ecdsa.Sign(rand.Reader, priv, utils.Hash(rawreq))
	if err != nil {
		panic(err)
	}
	R, _ := r.MarshalText()
	S, _ := s.MarshalText()
	req.Sig = &obcca.Signature{obcca.CryptoType_ECDSA, R, S}

	pbCert, err := node.callTLSCACreateCertificate(context.Background(), req)
	if err != nil {
		node.log.Error("Failed requesting tls certificate: %s", err)

		return nil, nil, err
	}

	node.log.Info("Verifing tls certificate...")

	tlsCert, err := utils.DERToX509Certificate(pbCert.Cert)
	certPK := tlsCert.PublicKey.(*ecdsa.PublicKey)
	utils.VerifySignCapability(priv, certPK)

	node.log.Info("Verifing tls certificate...done!")

	return priv, pbCert.Cert, nil
}
Exemple #4
0
func (node *nodeImpl) getEnrollmentCertificateFromECA(id, pw string) (interface{}, []byte, []byte, error) {
	priv, err := utils.NewECDSAKey()

	if err != nil {
		node.log.Error("Failed generating key [%s].", err.Error())

		return nil, nil, nil, err
	}

	// Prepare the request
	pubraw, _ := x509.MarshalPKIXPublicKey(&priv.PublicKey)
	req := &obcca.ECertCreateReq{
		Ts:  &protobuf.Timestamp{Seconds: time.Now().Unix(), Nanos: 0},
		Id:  &obcca.Identity{Id: id},
		Pw:  &obcca.Password{Pw: pw},
		Pub: &obcca.PublicKey{Type: obcca.CryptoType_ECDSA, Key: pubraw},
		Sig: nil}
	rawreq, _ := proto.Marshal(req)
	r, s, err := ecdsa.Sign(rand.Reader, priv, utils.Hash(rawreq))
	if err != nil {
		node.log.Error("Failed signing request [%s].", err.Error())

		return nil, nil, nil, err
	}
	R, _ := r.MarshalText()
	S, _ := s.MarshalText()
	req.Sig = &obcca.Signature{obcca.CryptoType_ECDSA, R, S}

	pbCert, key, err := node.callECACreateCertificate(context.Background(), req)
	if err != nil {
		node.log.Error("Failed requesting enrollment certificate [%s].", err.Error())

		return nil, nil, nil, err
	}

	node.log.Debug("Enrollment certificate hash [%s].", utils.EncodeBase64(utils.Hash(pbCert.Cert)))

	// Verify pbCert.Cert
	return priv, pbCert.Cert, key, nil
}
func (handler *eCertTransactionHandlerImpl) init(client *clientImpl) error {
	nonce, err := client.createTransactionNonce()
	if err != nil {
		client.node.log.Error("Failed initiliazing transaction handler [%s]", err)

		return err
	}

	handler.client = client
	handler.nonce = nonce
	handler.binding = utils.Hash(append(handler.client.node.enrollCert.Raw, handler.nonce...))

	return nil
}
func (handler *tCertTransactionHandlerImpl) init(tCertHandler *tCertHandlerImpl) error {
	nonce, err := tCertHandler.client.createTransactionNonce()
	if err != nil {
		tCertHandler.client.error("Failed initiliazing transaction handler [%s]", err)

		return err
	}

	handler.tCertHandler = tCertHandler
	handler.nonce = nonce
	handler.binding = utils.Hash(append(handler.tCertHandler.tCert.GetCertificate().Raw, nonce...))

	return nil
}
func createConfidentialECertHDeployTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
	uuid, err := util.GenerateUUID()
	if err != nil {
		return nil, nil, err
	}

	cds := &obc.ChaincodeDeploymentSpec{
		ChaincodeSpec: &obc.ChaincodeSpec{
			Type:                 obc.ChaincodeSpec_GOLANG,
			ChaincodeID:          &obc.ChaincodeID{Path: "Contract001"},
			CtorMsg:              nil,
			ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
		},
		EffectiveDate: nil,
		CodePackage:   nil,
	}

	otx, err := obc.NewChaincodeDeployTransaction(cds, uuid)
	if err != nil {
		return nil, nil, err
	}
	handler, err := deployer.GetEnrollmentCertificateHandler()
	if err != nil {
		return nil, nil, err
	}
	txHandler, err := handler.GetTransactionHandler()
	if err != nil {
		return nil, nil, err
	}
	tx, err := txHandler.NewChaincodeDeployTransaction(cds, uuid)

	// Check binding consistency
	binding, _ := txHandler.GetBinding()
	if !reflect.DeepEqual(binding, utils.Hash(append(handler.GetCertificate(), tx.Nonce...))) {
		t.Fatal("Binding is malformed!")
	}

	// Check confidentiality level
	if tx.ConfidentialityLevel != cds.ChaincodeSpec.ConfidentialityLevel {
		t.Fatal("Failed setting confidentiality level")
	}

	// Check metadata
	if !reflect.DeepEqual(cds.ChaincodeSpec.Metadata, tx.Metadata) {
		t.Fatal("Failed copying metadata")
	}

	return otx, tx, err
}
func createConfidentialTCertHQueryTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
	uuid, err := util.GenerateUUID()
	if err != nil {
		return nil, nil, err
	}

	cis := &obc.ChaincodeInvocationSpec{
		ChaincodeSpec: &obc.ChaincodeSpec{
			Type:                 obc.ChaincodeSpec_GOLANG,
			ChaincodeID:          &obc.ChaincodeID{Path: "Contract001"},
			CtorMsg:              nil,
			ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
		},
	}

	otx, err := obc.NewChaincodeExecute(cis, uuid, obc.Transaction_CHAINCODE_QUERY)
	if err != nil {
		return nil, nil, err
	}
	handler, err := invoker.GetTCertificateHandlerNext()
	if err != nil {
		return nil, nil, err
	}
	txHandler, err := handler.GetTransactionHandler()
	if err != nil {
		return nil, nil, err
	}
	tx, err := txHandler.NewChaincodeQuery(cis, uuid)

	// Check binding consistency
	binding, _ := txHandler.GetBinding()
	if !reflect.DeepEqual(binding, utils.Hash(append(handler.GetCertificate(), tx.Nonce...))) {
		t.Fatal("Binding is malformed!")
	}

	// Check confidentiality level
	if tx.ConfidentialityLevel != cis.ChaincodeSpec.ConfidentialityLevel {
		t.Fatal("Failed setting confidentiality level")
	}

	// Check metadata
	if !reflect.DeepEqual(cis.ChaincodeSpec.Metadata, tx.Metadata) {
		t.Fatal("Failed copying metadata")
	}

	return otx, tx, err
}
Exemple #9
0
func (validator *validatorImpl) GetStateEncryptor(deployTx, executeTx *obc.Transaction) (StateEncryptor, error) {
	// Check nonce
	if deployTx.Nonce == nil || len(deployTx.Nonce) == 0 {
		return nil, errors.New("Invalid deploy nonce.")
	}
	if executeTx.Nonce == nil || len(executeTx.Nonce) == 0 {
		return nil, errors.New("Invalid invoke nonce.")
	}
	// Check ChaincodeID
	if deployTx.ChaincodeID == nil {
		return nil, errors.New("Invalid deploy chaincodeID.")
	}
	if executeTx.ChaincodeID == nil {
		return nil, errors.New("Invalid execute chaincodeID.")
	}
	// Check that deployTx and executeTx refers to the same chaincode
	if !reflect.DeepEqual(deployTx.ChaincodeID, executeTx.ChaincodeID) {
		return nil, utils.ErrDirrentChaincodeID
	}

	validator.peer.node.log.Debug("Parsing transaction. Type [%s].", executeTx.Type.String())

	if executeTx.Type == obc.Transaction_CHAINCODE_QUERY {
		validator.peer.node.log.Debug("Parsing Query transaction...")

		// Compute deployTxKey key from the deploy transaction. This is used to decrypt the actual state
		// of the chaincode
		deployTxKey := utils.HMAC(validator.peer.node.enrollChainKey, deployTx.Nonce)

		// Compute the key used to encrypt the result of the query
		queryKey := utils.HMACTruncated(validator.peer.node.enrollChainKey, append([]byte{6}, executeTx.Nonce...), utils.AESKeyLength)

		// Init the state encryptor
		se := queryStateEncryptor{}
		err := se.init(validator.peer.node.log, queryKey, deployTxKey)
		if err != nil {
			return nil, err
		}

		return &se, nil
	}

	// Compute deployTxKey key from the deploy transaction
	deployTxKey := utils.HMAC(validator.peer.node.enrollChainKey, deployTx.Nonce)

	// Mask executeTx.Nonce
	executeTxNonce := utils.HMACTruncated(deployTxKey, utils.Hash(executeTx.Nonce), utils.NonceSize)

	// Compute stateKey to encrypt the states and nonceStateKey to generates IVs. This
	// allows validators to reach consesus
	stateKey := utils.HMACTruncated(deployTxKey, append([]byte{3}, executeTxNonce...), utils.AESKeyLength)
	nonceStateKey := utils.HMAC(deployTxKey, append([]byte{4}, executeTxNonce...))

	// Init the state encryptor
	se := stateEncryptorImpl{}
	err := se.init(validator.peer.node.log, stateKey, nonceStateKey, deployTxKey, executeTxNonce)
	if err != nil {
		return nil, err
	}

	return &se, nil
}
func requestTLSCertificate(t *testing.T) {
	var opts []grpc.DialOption

	creds, err := credentials.NewClientTLSFromFile(viper.GetString("server.tls.certfile"), "tlsca")
	if err != nil {
		t.Logf("Failed creating credentials for TLS-CA client: %s", err)
		t.Fail()
	}

	opts = append(opts, grpc.WithTransportCredentials(creds))
	sockP, err := grpc.Dial(viper.GetString("peer.pki.tlsca.paddr"), opts...)
	if err != nil {
		t.Logf("Failed dialing in: %s", err)
		t.Fail()
	}

	defer sockP.Close()

	tlscaP := obcca.NewTLSCAPClient(sockP)

	// Prepare the request
	id := "peer"
	priv, err := utils.NewECDSAKey()

	if err != nil {
		t.Logf("Failed generating key: %s", err)
		t.Fail()
	}

	uuid, err := util.GenerateUUID()
	if err != nil {
		t.Logf("Failed generating uuid: %s", err)
		t.Fail()
	}

	pubraw, _ := x509.MarshalPKIXPublicKey(&priv.PublicKey)
	now := time.Now()
	timestamp := google_protobuf.Timestamp{int64(now.Second()), int32(now.Nanosecond())}

	req := &obcca.TLSCertCreateReq{
		&timestamp,
		&obcca.Identity{Id: id + "-" + uuid},
		&obcca.PublicKey{
			Type: obcca.CryptoType_ECDSA,
			Key:  pubraw,
		}, nil}

	rawreq, _ := proto.Marshal(req)
	r, s, err := ecdsa.Sign(rand.Reader, priv, utils.Hash(rawreq))

	if err != nil {
		t.Logf("Failed signing the request: %s", err)
		t.Fail()
	}

	R, _ := r.MarshalText()
	S, _ := s.MarshalText()
	req.Sig = &obcca.Signature{obcca.CryptoType_ECDSA, R, S}

	resp, err := tlscaP.CreateCertificate(context.Background(), req)
	if err != nil {
		t.Logf("Failed requesting tls certificate: %s", err)
		t.Fail()
	}

	storePrivateKeyInClear("tls_peer.priv", priv, t)
	storeCert("tls_peer.cert", resp.Cert.Cert, t)
	storeCert("tls_peer.ca", resp.RootCert.Cert, t)
}
Exemple #11
0
func (node *nodeImpl) getEnrollmentCertificateFromECA(id, pw string) (interface{}, []byte, []byte, error) {
	// Get a new ECA Client
	sock, ecaP, err := node.getECAClient()
	defer sock.Close()

	// Run the protocol

	signPriv, err := utils.NewECDSAKey()
	if err != nil {
		node.log.Error("Failed generating ECDSA key [%s].", err.Error())

		return nil, nil, nil, err
	}
	signPub, err := x509.MarshalPKIXPublicKey(&signPriv.PublicKey)
	if err != nil {
		node.log.Error("Failed mashalling ECDSA key [%s].", err.Error())

		return nil, nil, nil, err
	}

	encPriv, err := utils.NewECDSAKey()
	if err != nil {
		node.log.Error("Failed generating Encryption key [%s].", err.Error())

		return nil, nil, nil, err
	}
	encPub, err := x509.MarshalPKIXPublicKey(&encPriv.PublicKey)
	if err != nil {
		node.log.Error("Failed marshalling Encryption key [%s].", err.Error())

		return nil, nil, nil, err
	}

	req := &obcca.ECertCreateReq{&protobuf.Timestamp{Seconds: time.Now().Unix(), Nanos: 0},
		&obcca.Identity{id},
		&obcca.Token{Tok: []byte(pw)},
		&obcca.PublicKey{obcca.CryptoType_ECDSA, signPub},
		&obcca.PublicKey{obcca.CryptoType_ECDSA, encPub},
		nil}

	resp, err := ecaP.CreateCertificatePair(context.Background(), req)
	if err != nil {
		node.log.Error("Failed invoking CreateCertficatePair [%s].", err.Error())

		return nil, nil, nil, err
	}

	//out, err := rsa.DecryptPKCS1v15(rand.Reader, encPriv, resp.Tok.Tok)
	spi := ecies.NewSPI()
	eciesKey, err := spi.NewPrivateKey(nil, encPriv)
	if err != nil {
		node.log.Error("Failed parsing decrypting key [%s].", err.Error())

		return nil, nil, nil, err
	}

	ecies, err := spi.NewAsymmetricCipherFromPublicKey(eciesKey)
	if err != nil {
		node.log.Error("Failed creating asymmetrinc cipher [%s].", err.Error())

		return nil, nil, nil, err
	}

	out, err := ecies.Process(resp.Tok.Tok)
	if err != nil {
		node.log.Error("Failed decrypting toke [%s].", err.Error())

		return nil, nil, nil, err
	}

	req.Tok.Tok = out
	req.Sig = nil

	hash := utils.NewHash()
	raw, _ := proto.Marshal(req)
	hash.Write(raw)

	r, s, err := ecdsa.Sign(rand.Reader, signPriv, hash.Sum(nil))
	if err != nil {
		node.log.Error("Failed signing [%s].", err.Error())

		return nil, nil, nil, err
	}
	R, _ := r.MarshalText()
	S, _ := s.MarshalText()
	req.Sig = &obcca.Signature{obcca.CryptoType_ECDSA, R, S}

	resp, err = ecaP.CreateCertificatePair(context.Background(), req)
	if err != nil {
		node.log.Error("Failed invoking CreateCertificatePair [%s].", err.Error())

		return nil, nil, nil, err
	}

	// Verify response

	// Verify cert for signing
	node.log.Debug("Enrollment certificate for signing [%s]", utils.EncodeBase64(utils.Hash(resp.Certs.Sign)))

	x509SignCert, err := utils.DERToX509Certificate(resp.Certs.Sign)
	if err != nil {
		node.log.Error("Failed parsing signing enrollment certificate for signing: [%s]", err)

		return nil, nil, nil, err
	}

	_, err = utils.GetCriticalExtension(x509SignCert, ECertSubjectRole)
	if err != nil {
		node.log.Error("Failed parsing ECertSubjectRole in enrollment certificate for signing: [%s]", err)

		return nil, nil, nil, err
	}

	err = utils.CheckCertAgainstSKAndRoot(x509SignCert, signPriv, node.ecaCertPool)
	if err != nil {
		node.log.Error("Failed checking signing enrollment certificate for signing: [%s]", err)

		return nil, nil, nil, err
	}

	// Verify cert for encrypting
	node.log.Debug("Enrollment certificate for encrypting [%s]", utils.EncodeBase64(utils.Hash(resp.Certs.Enc)))

	x509EncCert, err := utils.DERToX509Certificate(resp.Certs.Enc)
	if err != nil {
		node.log.Error("Failed parsing signing enrollment certificate for encrypting: [%s]", err)

		return nil, nil, nil, err
	}

	_, err = utils.GetCriticalExtension(x509EncCert, ECertSubjectRole)
	if err != nil {
		node.log.Error("Failed parsing ECertSubjectRole in enrollment certificate for encrypting: [%s]", err)

		return nil, nil, nil, err
	}

	err = utils.CheckCertAgainstSKAndRoot(x509EncCert, encPriv, node.ecaCertPool)
	if err != nil {
		node.log.Error("Failed checking signing enrollment certificate for encrypting: [%s]", err)

		return nil, nil, nil, err
	}

	// END

	return signPriv, resp.Certs.Sign, resp.Chain.Tok, nil
}
Exemple #12
0
func (peer *peerImpl) GetTransactionBinding(tx *obc.Transaction) ([]byte, error) {
	return utils.Hash(append(tx.Cert, tx.Nonce...)), nil
}