Esempio n. 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
}
Esempio n. 2
0
// Verify checks that signature if a valid signature of message under vkID's verification key.
// If the verification succeeded, Verify returns nil meaning no error occurred.
// If vkID is nil, then the signature is verified against this validator's verification key.
func (validator *validatorImpl) Verify(vkID, signature, message []byte) error {
	if len(vkID) == 0 {
		return fmt.Errorf("Invalid peer id. It is empty.")
	}
	if len(signature) == 0 {
		return fmt.Errorf("Invalid signature. It is empty.")
	}
	if len(message) == 0 {
		return fmt.Errorf("Invalid message. It is empty.")
	}

	cert, err := validator.getEnrollmentCert(vkID)
	if err != nil {
		validator.peer.node.log.Error("Failed getting enrollment cert ", utils.EncodeBase64(vkID), err)

		return err
	}

	vk := cert.PublicKey.(*ecdsa.PublicKey)

	ok, err := validator.verify(vk, message, signature)
	if err != nil {
		validator.peer.node.log.Error("Failed verifying signature for ", utils.EncodeBase64(vkID), err)

		return err
	}

	if !ok {
		validator.peer.node.log.Error("Failed invalid signature for ", utils.EncodeBase64(vkID))

		return utils.ErrInvalidSignature
	}

	return nil
}
Esempio n. 3
0
func (validator *validatorImpl) getEnrollmentCert(id []byte) (*x509.Certificate, error) {
	sid := utils.EncodeBase64(id)

	validator.peer.node.log.Debug("Getting enrollment certificate for [%d]", sid)

	if cert := validator.enrollCerts[sid]; cert != nil {
		validator.peer.node.log.Debug("Enrollment certificate for [%d] already in memory.", sid)

		return cert, nil
	}

	// Retrieve from the DB or from the ECA in case
	validator.peer.node.log.Debug("Retrieve Enrollment certificate for [%d]...", sid)
	rawCert, err := validator.peer.node.ks.GetSignEnrollmentCert(id, validator.getEnrollmentCertByHashFromECA)
	if err != nil {
		validator.peer.node.log.Error("Failed getting enrollment certificate for [%s]: [%s]", sid, err)
	}

	validator.peer.node.log.Debug("Enrollment certificate for [%s] = [%s]", sid, utils.EncodeBase64(rawCert))

	cert, err := utils.DERToX509Certificate(rawCert)
	if err != nil {
		validator.peer.node.log.Error("Failed parsing enrollment certificate for [%s]: [%s],[%s]", sid, utils.EncodeBase64(rawCert), err)
	}

	validator.enrollCerts[sid] = cert

	return cert, nil
}
Esempio n. 4
0
func (node *nodeImpl) verify(verKey interface{}, msg, signature []byte) (bool, error) {
	node.log.Debug("Verifing signature [%s] against message [%s].",
		utils.EncodeBase64(signature),
		utils.EncodeBase64(msg),
	)

	return utils.ECDSAVerify(verKey, msg, signature)
}
Esempio n. 5
0
func (node *nodeImpl) verifyWithEnrollmentCert(msg, signature []byte) (bool, error) {
	node.log.Debug("Verifing signature [%s] against message [%s].",
		utils.EncodeBase64(signature),
		utils.EncodeBase64(msg),
	)

	return utils.ECDSAVerify(node.enrollCert.PublicKey, msg, signature)
}
Esempio n. 6
0
func isEqual(src, dst *obc.Transaction) error {
	if !reflect.DeepEqual(src.Payload, dst.Payload) {
		return fmt.Errorf("Different Payload [%s]!=[%s].", utils.EncodeBase64(src.Payload), utils.EncodeBase64(dst.Payload))
	}

	if !reflect.DeepEqual(src.ChaincodeID, dst.ChaincodeID) {
		return fmt.Errorf("Different ChaincodeID [%s]!=[%s].", utils.EncodeBase64(src.ChaincodeID), utils.EncodeBase64(dst.ChaincodeID))
	}

	if !reflect.DeepEqual(src.Metadata, dst.Metadata) {
		return fmt.Errorf("Different Metadata [%s]!=[%s].", utils.EncodeBase64(src.Metadata), utils.EncodeBase64(dst.Metadata))
	}

	return nil
}
Esempio n. 7
0
// GetTCertHandlerFromDER returns a CertificateHandler whose certificate is the one passed
func (client *clientImpl) GetTCertificateHandlerFromDER(tCertDER []byte) (CertificateHandler, error) {
	// Verify that the client is initialized
	if !client.isInitialized {
		return nil, utils.ErrNotInitialized
	}

	client.node.log.Info("Getting a CertificateHandler for TCert [%s]", utils.EncodeBase64(tCertDER))

	// Validate the transaction certificate
	tCert, err := client.validateTCert(tCertDER)
	if err != nil {
		client.node.log.Warning("Failed validating transaction certificate [%s].", err)

		return nil, err
	}

	// Return the handler
	handler := &tCertHandlerImpl{}
	err = handler.initX509(client, tCert)
	if err != nil {
		client.node.log.Error("Failed getting handler [%s].", err.Error())
		return nil, err
	}

	return handler, nil
}
Esempio n. 8
0
func (node *nodeImpl) retrieveTLSCertificate(id, affiliation string) error {
	key, tlsCertRaw, err := node.getTLSCertificateFromTLSCA(id, affiliation)
	if err != nil {
		node.log.Error("Failed getting tls certificate [id=%s] %s", id, err)

		return err
	}
	node.log.Debug("TLS Cert [%s]", utils.EncodeBase64(tlsCertRaw))

	node.log.Info("Storing TLS key and certificate for user [%s]...", id)

	// Store tls key.
	if err := node.ks.storePrivateKeyInClear(node.conf.getTLSKeyFilename(), key); err != nil {
		node.log.Error("Failed storing tls key [id=%s]: %s", id, err)
		return err
	}

	// Store tls cert
	if err := node.ks.storeCert(node.conf.getTLSCertFilename(), tlsCertRaw); err != nil {
		node.log.Error("Failed storing tls certificate [id=%s]: %s", id, err)
		return err
	}

	return nil
}
Esempio n. 9
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
}
Esempio n. 10
0
func (validator *validatorImpl) signWithEnrollmentKey(msg []byte) ([]byte, error) {
	sigma, err := utils.ECDSASign(validator.peer.node.enrollPrivKey, msg)

	validator.peer.node.log.Debug("Signing message [%s], sigma [%s].", utils.EncodeBase64(msg), utils.EncodeBase64(sigma))

	return sigma, err
}
Esempio n. 11
0
func (validator *validatorImpl) getEnrollmentCert(id []byte) (*x509.Certificate, error) {
	if len(id) == 0 {
		return nil, fmt.Errorf("Invalid peer id. It is empty.")
	}

	sid := utils.EncodeBase64(id)

	validator.debug("Getting enrollment certificate for [%s]", sid)

	if cert := validator.enrollCerts[sid]; cert != nil {
		validator.debug("Enrollment certificate for [%s] already in memory.", sid)
		return cert, nil
	}

	// Retrieve from the DB or from the ECA in case
	validator.debug("Retrieve Enrollment certificate for [%s]...", sid)
	rawCert, err := validator.ks.GetSignEnrollmentCert(id, validator.getEnrollmentCertByHashFromECA)
	if err != nil {
		validator.error("Failed getting enrollment certificate for [%s]: [%s]", sid, err)

		return nil, err
	}

	cert, err := utils.DERToX509Certificate(rawCert)
	if err != nil {
		validator.error("Failed parsing enrollment certificate for [%s]: [% x],[% x]", sid, rawCert, err)

		return nil, err
	}

	validator.enrollCerts[sid] = cert

	return cert, nil
}
Esempio n. 12
0
func (node *nodeImpl) retrieveTLSCertificate(id, affiliation string) error {
	key, tlsCertRaw, err := node.getTLSCertificateFromTLSCA(id, affiliation)
	if err != nil {
		node.log.Error("Failed getting tls certificate [id=%s] %s", id, err)

		return err
	}
	node.log.Info("Register:cert %s", utils.EncodeBase64(tlsCertRaw))

	// Store enrollment  key
	node.log.Info("Storing enrollment key and certificate for user [%s]...", id)

	rawKey, err := utils.PrivateKeyToPEM(key)
	if err != nil {
		node.log.Error("Failed converting tls key to PEM [id=%s]: %s", id, err)
		return err
	}

	err = ioutil.WriteFile(node.conf.getTLSKeyPath(), rawKey, 0700)
	if err != nil {
		node.log.Error("Failed storing tls key [id=%s]: %s", id, err)
		return err
	}

	// Store tls cert
	err = ioutil.WriteFile(node.conf.getTLSCertPath(), utils.DERCertToPEM(tlsCertRaw), 0700)
	if err != nil {
		node.log.Error("Failed storing tls certificate [id=%s]: %s", id, err)
		return err
	}

	return nil
}
Esempio n. 13
0
func (node *nodeImpl) retrieveECACertsChain(userID string) error {
	// Retrieve ECA certificate and verify it
	ecaCertRaw, err := node.getECACertificate()
	if err != nil {
		node.log.Error("Failed getting ECA certificate [%s].", err.Error())

		return err
	}
	node.log.Debug("ECA certificate [%s].", utils.EncodeBase64(ecaCertRaw))

	// TODO: Test ECA cert againt root CA
	// TODO: check responce.Cert against rootCA
	x509ECACert, err := utils.DERToX509Certificate(ecaCertRaw)
	if err != nil {
		node.log.Error("Failed parsing ECA certificate [%s].", err.Error())

		return err
	}

	// Prepare ecaCertPool
	node.ecaCertPool = x509.NewCertPool()
	node.ecaCertPool.AddCert(x509ECACert)

	// Store ECA cert
	node.log.Debug("Storing ECA certificate for [%s]...", userID)

	if err := node.ks.storeCert(node.conf.getECACertsChainFilename(), ecaCertRaw); err != nil {
		node.log.Error("Failed storing eca certificate [%s].", err.Error())
		return err
	}

	return nil
}
Esempio n. 14
0
func (client *clientImpl) validateTCert(tCertDER []byte) (*x509.Certificate, error) {
	client.node.log.Debug("Validating TCert [%s]", utils.EncodeBase64(tCertDER))

	// DER to x509
	x509Cert, err := utils.DERToX509Certificate(tCertDER)
	if err != nil {
		client.node.log.Debug("Failed parsing certificate: [%s].", err)

		return nil, err
	}

	// Handle Critical Extension TCertEncTCertIndex
	if _, err = utils.GetCriticalExtension(x509Cert, utils.TCertEncTCertIndex); err != nil {
		client.node.log.Error("Failed getting extension TCERT_ENC_TCERTINDEX [%s].", err.Error())

		return nil, err
	}

	// Verify certificate against root
	if _, err := utils.CheckCertAgainRoot(x509Cert, client.node.tcaCertPool); err != nil {
		client.node.log.Warning("Warning verifing certificate [%s].", err.Error())

		return nil, err
	}

	return x509Cert, nil
}
Esempio n. 15
0
func (node *nodeImpl) retrieveTCACertsChain(userID string) error {
	// Retrieve TCA certificate and verify it
	tcaCertRaw, err := node.getTCACertificate()
	if err != nil {
		node.log.Error("Failed getting TCA certificate [%s].", err.Error())

		return err
	}
	node.log.Debug("TCA certificate [%s]", utils.EncodeBase64(tcaCertRaw))

	// TODO: Test TCA cert againt root CA
	_, err = utils.DERToX509Certificate(tcaCertRaw)
	if err != nil {
		node.log.Error("Failed parsing TCA certificate [%s].", err.Error())

		return err
	}

	// Store TCA cert
	node.log.Debug("Storing TCA certificate for validator [%s]...", userID)

	err = ioutil.WriteFile(node.conf.getTCACertsChainPath(), utils.DERCertToPEM(tcaCertRaw), 0700)
	if err != nil {
		node.log.Error("Failed storing tca certificate [%s].", err.Error())
		return err
	}

	return nil
}
Esempio n. 16
0
func (validator *validatorImpl) sign(signKey interface{}, msg []byte) ([]byte, error) {
	sigma, err := utils.ECDSASign(signKey, msg)

	validator.peer.node.log.Debug("Signing message [%s], sigma [%s].", utils.EncodeBase64(msg), utils.EncodeBase64(sigma))

	return sigma, err
}
Esempio n. 17
0
func (validator *validatorImpl) getEnrollmentCertByHashFromECA(id []byte) ([]byte, []byte, error) {
	// Prepare the request
	validator.peer.node.log.Debug("Reading certificate for hash [%s]", utils.EncodeBase64(id))

	req := &obcca.Hash{Hash: id}
	responce, err := validator.peer.node.callECAReadCertificateByHash(context.Background(), req)
	if err != nil {
		validator.peer.node.log.Error("Failed requesting enrollment certificate [%s].", err.Error())

		return nil, nil, err
	}

	validator.peer.node.log.Debug("Certificate for hash [%s] = [%s][%s]", utils.EncodeBase64(id), utils.EncodeBase64(responce.Sign), utils.EncodeBase64(responce.Enc))

	// Verify responce.Sign
	x509Cert, err := utils.DERToX509Certificate(responce.Sign)
	if err != nil {
		validator.peer.node.log.Error("Failed parsing signing enrollment certificate for encrypting: [%s]", err)

		return nil, nil, err
	}

	// Check role
	roleRaw, err := utils.GetCriticalExtension(x509Cert, ECertSubjectRole)
	if err != nil {
		validator.peer.node.log.Error("Failed parsing ECertSubjectRole in enrollment certificate for signing: [%s]", err)

		return nil, nil, err
	}

	role, err := strconv.ParseInt(string(roleRaw), 10, len(roleRaw)*8)
	if err != nil {
		validator.peer.node.log.Error("Failed parsing ECertSubjectRole in enrollment certificate for signing: [%s]", err)

		return nil, nil, err
	}

	if obcca.Role(role) != obcca.Role_VALIDATOR {
		validator.peer.node.log.Error("Invalid ECertSubjectRole in enrollment certificate for signing. Not a validator: [%s]", err)

		return nil, nil, err
	}

	return responce.Sign, responce.Enc, nil
}
Esempio n. 18
0
func (client *clientImpl) encryptTx(tx *obc.Transaction) error {

	if len(tx.Nonce) == 0 {
		return errors.New("Failed encrypting payload. Invalid nonce.")
	}

	// Derive key
	txKey := utils.HMAC(client.node.enrollChainKey, tx.Nonce)

	//	client.node.log.Info("Deriving from :", utils.EncodeBase64(client.node.enrollChainKey))
	//	client.node.log.Info("Nonce  ", utils.EncodeBase64(tx.Nonce))
	//	client.node.log.Info("Derived key  ", utils.EncodeBase64(txKey))

	// Encrypt Payload
	payloadKey := utils.HMACTruncated(txKey, []byte{1}, utils.AESKeyLength)
	encryptedPayload, err := utils.CBCPKCS7Encrypt(payloadKey, tx.Payload)
	if err != nil {
		return err
	}
	tx.Payload = encryptedPayload

	// Encrypt ChaincodeID
	chaincodeIDKey := utils.HMACTruncated(txKey, []byte{2}, utils.AESKeyLength)
	encryptedChaincodeID, err := utils.CBCPKCS7Encrypt(chaincodeIDKey, tx.ChaincodeID)
	if err != nil {
		return err
	}
	tx.ChaincodeID = encryptedChaincodeID

	// Encrypt Metadata
	if len(tx.Metadata) != 0 {
		metadataKey := utils.HMACTruncated(txKey, []byte{3}, utils.AESKeyLength)
		encryptedMetadata, err := utils.CBCPKCS7Encrypt(metadataKey, tx.Metadata)
		if err != nil {
			return err
		}
		tx.Metadata = encryptedMetadata
	}

	client.node.log.Debug("Encrypted ChaincodeID [%s].", utils.EncodeBase64(tx.ChaincodeID))
	client.node.log.Debug("Encrypted Payload [%s].", utils.EncodeBase64(tx.Payload))
	client.node.log.Debug("Encrypted Metadata [%s].", utils.EncodeBase64(tx.Metadata))

	return nil
}
Esempio n. 19
0
func (ks *keyStore) selectNextTCert() ([]byte, error) {
	ks.log.Debug("Select next TCert...")

	// Open transaction
	tx, err := ks.sqlDB.Begin()
	if err != nil {
		ks.log.Error("Failed beginning transaction [%s].", err.Error())

		return nil, err
	}

	// Get the first row available
	var id int
	var cert []byte
	row := ks.sqlDB.QueryRow("SELECT id, cert FROM TCerts")
	err = row.Scan(&id, &cert)

	if err == sql.ErrNoRows {
		return nil, nil
	} else if err != nil {
		ks.log.Error("Error during select [%s].", err.Error())

		return nil, err
	}

	ks.log.Debug("id [%d]", id)
	ks.log.Debug("cert [%s].", utils.EncodeBase64(cert))

	// TODO: rather than removing, move the cert to another table
	// which stores the TCerts used

	// Remove that row
	ks.log.Debug("Removing row with id [%d]...", id)

	if _, err := tx.Exec("DELETE FROM TCerts WHERE id = ?", id); err != nil {
		ks.log.Error("Failed removing row [%d] [%s].", id, err.Error())

		tx.Rollback()

		return nil, err
	}

	ks.log.Debug("Removing row with id [%d]...done", id)

	// Finalize
	err = tx.Commit()
	if err != nil {
		ks.log.Error("Failed commiting [%s].", err.Error())
		tx.Rollback()

		return nil, err
	}

	ks.log.Debug("Select next TCert...done!")

	return cert, nil
}
Esempio n. 20
0
// Verify checks that signature if a valid signature of message under vkID's verification key.
// If the verification succeeded, Verify returns nil meaning no error occurred.
// If vkID is nil, then the signature is verified against this validator's verification key.
func (validator *validatorImpl) Verify(vkID, signature, message []byte) error {
	cert, err := validator.getEnrollmentCert(vkID)
	if err != nil {
		validator.peer.node.log.Error("Failed getting enrollment cert ", utils.EncodeBase64(vkID), err)
	}

	vk := cert.PublicKey.(*ecdsa.PublicKey)

	ok, err := validator.verify(vk, message, signature)
	if err != nil {
		validator.peer.node.log.Error("Failed verifying signature for ", utils.EncodeBase64(vkID), err)
	}

	if !ok {
		validator.peer.node.log.Error("Failed invalid signature for ", utils.EncodeBase64(vkID))

		return utils.ErrInvalidSignature
	}

	return nil
}
Esempio n. 21
0
func (validator *validatorImpl) getEnrollmentCert(id []byte) (*x509.Certificate, error) {
	sid := utils.EncodeBase64(id)

	if cert := validator.enrollCerts[sid]; cert != nil {
		return cert, nil
	}

	// Retrieve from the DB or from the ECA in case
	rawCert, err := validator.peer.node.ks.GetEnrollmentCert(id, validator.getEnrollmentCertByHashFromECA)
	if err != nil {
		validator.peer.node.log.Error("Failed getting enrollment certificate for ", sid, err)
	}

	cert, err := utils.DERToX509Certificate(rawCert)
	if err != nil {
		validator.peer.node.log.Error("Failed parsing enrollment certificate for ", sid, utils.EncodeBase64(rawCert))
	}

	validator.enrollCerts[sid] = cert

	return cert, nil
}
Esempio n. 22
0
func (client *clientImpl) encryptTx(tx *obc.Transaction) error {

	if tx.Nonce == nil || len(tx.Nonce) == 0 {
		return errors.New("Failed encrypting payload. Invalid nonce.")
	}

	// Derive key
	txKey := utils.HMAC(client.node.enrollChainKey, tx.Nonce)

	//	client.node.log.Info("Deriving from :", utils.EncodeBase64(client.node.enrollChainKey))
	//	client.node.log.Info("Nonce  ", utils.EncodeBase64(tx.Nonce))
	//	client.node.log.Info("Derived key  ", utils.EncodeBase64(txKey))

	// Encrypt using the derived key
	payloadKey := utils.HMACTruncated(txKey, []byte{1}, utils.AESKeyLength)
	encryptedPayload, err := utils.CBCPKCS7Encrypt(payloadKey, tx.Payload)
	if err != nil {
		return err
	}
	tx.EncryptedPayload = encryptedPayload
	tx.Payload = nil

	chaincodeIDKey := utils.HMACTruncated(txKey, []byte{2}, utils.AESKeyLength)
	rawChaincodeID, err := proto.Marshal(tx.ChaincodeID)
	if err != nil {
		return err
	}
	tx.EncryptedChaincodeID, err = utils.CBCPKCS7Encrypt(chaincodeIDKey, rawChaincodeID)
	if err != nil {
		return err
	}
	tx.ChaincodeID = nil

	client.node.log.Debug("Encrypted Payload [%s].", utils.EncodeBase64(tx.EncryptedPayload))
	client.node.log.Debug("Encrypted ChaincodeID [%s].", utils.EncodeBase64(tx.EncryptedChaincodeID))

	return nil
}
Esempio n. 23
0
func (client *clientImpl) newChaincodeExecuteUsingTCert(chaincodeInvocation *obc.ChaincodeInvocationSpec, uuid string, rawTCert []byte, nonce []byte) (*obc.Transaction, error) {
	/// Create a new transaction
	tx, err := client.createExecuteTx(chaincodeInvocation, uuid, nonce)
	if err != nil {
		client.node.log.Error("Failed creating new execute transaction [%s].", err.Error())
		return nil, err
	}

	// Sign the transaction

	// Append the certificate to the transaction
	client.node.log.Debug("Appending certificate [%s].", utils.EncodeBase64(rawTCert))
	tx.Cert = rawTCert

	// Sign the transaction and append the signature
	// 1. Marshall tx to bytes
	rawTx, err := proto.Marshal(tx)
	if err != nil {
		client.node.log.Error("Failed marshaling tx [%s].", err.Error())
		return nil, err
	}

	// 2. Sign rawTx and check signature
	client.node.log.Debug("Signing tx [%s].", utils.EncodeBase64(rawTx))
	rawSignature, err := client.signUsingTCertDER(rawTCert, rawTx)
	if err != nil {
		client.node.log.Error("Failed creating signature [%s].", err.Error())
		return nil, err
	}

	// 3. Append the signature
	tx.Signature = rawSignature

	client.node.log.Debug("Appending signature [%s].", utils.EncodeBase64(rawSignature))

	return tx, nil
}
Esempio n. 24
0
func (client *clientImpl) newChaincodeQueryUsingECert(chaincodeInvocation *obc.ChaincodeInvocationSpec, uuid string, nonce []byte) (*obc.Transaction, error) {
	// Create a new transaction
	tx, err := client.createQueryTx(chaincodeInvocation, uuid, nonce)
	if err != nil {
		client.node.log.Error("Failed creating new query transaction [%s].", err.Error())
		return nil, err
	}

	// Sign the transaction

	// Append the certificate to the transaction
	client.node.log.Debug("Appending certificate [%s].", utils.EncodeBase64(client.node.enrollCert.Raw))
	tx.Cert = client.node.enrollCert.Raw

	// Sign the transaction and append the signature
	// 1. Marshall tx to bytes
	rawTx, err := proto.Marshal(tx)
	if err != nil {
		client.node.log.Error("Failed marshaling tx [%s].", err.Error())
		return nil, err
	}

	// 2. Sign rawTx and check signature
	client.node.log.Debug("Signing tx [%s].", utils.EncodeBase64(rawTx))
	rawSignature, err := client.node.signWithEnrollmentKey(rawTx)
	if err != nil {
		client.node.log.Error("Failed creating signature [%s].", err.Error())
		return nil, err
	}

	// 3. Append the signature
	tx.Signature = rawSignature

	client.node.log.Debug("Appending signature [%s].", utils.EncodeBase64(rawSignature))

	return tx, nil
}
Esempio n. 25
0
func (client *clientImpl) tcaCreateCertificateSet(num int) ([]byte, [][]byte, error) {
	sockP, err := grpc.Dial(client.node.conf.getTCAPAddr(), grpc.WithInsecure())
	if err != nil {
		client.node.log.Error("Failed tca dial in [%s].", err.Error())

		return nil, nil, err
	}
	defer sockP.Close()

	tcaP := obcca.NewTCAPClient(sockP)

	now := time.Now()
	timestamp := google_protobuf.Timestamp{int64(now.Second()), int32(now.Nanosecond())}
	req := &obcca.TCertCreateSetReq{
		&timestamp,
		&obcca.Identity{Id: client.node.enrollID},
		uint32(num),
		nil,
	}
	rawReq, err := proto.Marshal(req)
	if err != nil {
		client.node.log.Error("Failed marshaling request [%s] [%s].", err.Error())
		return nil, nil, err
	}

	// 2. Sign rawReq
	client.node.log.Debug("Signing req  ", utils.EncodeBase64(rawReq))
	r, s, err := client.node.ecdsaSignWithEnrollmentKey(rawReq)
	if err != nil {
		client.node.log.Error("Failed creating signature [%s] [%s].", err.Error())
		return nil, nil, err
	}

	R, _ := r.MarshalText()
	S, _ := s.MarshalText()

	// 3. Append the signature
	req.Sig = &obcca.Signature{obcca.CryptoType_ECDSA, R, S}

	// 4. Send request
	certSet, err := tcaP.CreateCertificateSet(context.Background(), req)
	if err != nil {
		client.node.log.Error("Failed requesting tca create certificate set [%s].", err.Error())

		return nil, nil, err
	}

	return certSet.Key, certSet.Certs, nil
}
Esempio n. 26
0
func (validator *validatorImpl) getEnrollmentCertByHashFromECA(id []byte) ([]byte, error) {
	// Prepare the request
	validator.peer.node.log.Debug("Reading certificate for hash " + utils.EncodeBase64(id))

	req := &obcca.ECertReadReq{Id: &obcca.Identity{Id: ""}, Hash: id}
	pbCert, err := validator.peer.node.callECAReadCertificate(context.Background(), req)
	if err != nil {
		validator.peer.node.log.Error("Failed requesting enrollment certificate [%s].", err.Error())

		return nil, err
	}

	// TODO Verify pbCert.Cert
	return pbCert.Cert, nil
}
Esempio n. 27
0
func (node *nodeImpl) retrieveEnrollmentData(userID, pwd string) error {
	key, enrollCertRaw, enrollChainKey, err := node.getEnrollmentCertificateFromECA(userID, pwd)
	if err != nil {
		node.log.Error("Failed getting enrollment certificate [id=%s]  ", userID, err)

		return err
	}
	node.log.Debug("Enrollment certificate [%s].", utils.EncodeBase64(enrollCertRaw))
	//	validatorLogger.Info("Register:key  ", utils.EncodeBase64(key))

	// Store enrollment  key
	node.log.Debug("Storing enrollment data for user [%s]...", userID)

	rawKey, err := utils.PrivateKeyToPEM(key)
	if err != nil {
		node.log.Error("Failed converting enrollment key to PEM [id=%s]: ", userID, err)
		return err
	}

	err = ioutil.WriteFile(node.conf.getEnrollmentKeyPath(), rawKey, 0700)
	if err != nil {
		node.log.Error("Failed storing enrollment key [id=%s]: ", userID, err)
		return err
	}

	// Store enrollment cert
	err = ioutil.WriteFile(node.conf.getEnrollmentCertPath(), utils.DERCertToPEM(enrollCertRaw), 0700)
	if err != nil {
		node.log.Error("Failed storing enrollment certificate [id=%s]: ", userID, err)
		return err
	}

	// Store enrollment id
	err = ioutil.WriteFile(node.conf.getEnrollmentIDPath(), []byte(userID), 0700)
	if err != nil {
		node.log.Error("Failed storing enrollment certificate [id=%s]: ", userID, err)
		return err
	}

	// Store enrollment chain key
	err = ioutil.WriteFile(node.conf.getEnrollmentChainKeyPath(), utils.AEStoPEM(enrollChainKey), 0700)
	if err != nil {
		node.log.Error("Failed storing enrollment chain key [id=%s]: ", userID, err)
		return err
	}

	return nil
}
Esempio n. 28
0
// getNextTCert returns the next available (not yet used) transaction certificate
// corresponding to the tuple (cert, signing key)
func (client *clientImpl) getNextTCert() ([]byte, error) {
	client.node.log.Debug("Getting next TCert...")
	rawCert, err := client.node.ks.GetNextTCert(client.getTCertsFromTCA)
	if err != nil {
		client.node.log.Error("Failed accessing db [%s].", err.Error())

		return nil, err
	}

	// rawCert and rawKey are supposed to have been already verified at this point.
	client.node.log.Debug("Cert [%s].", utils.EncodeBase64(rawCert))
	//	client.node.log.Info("getNextTCert:key  ", utils.EncodeBase64(rawKey))

	client.node.log.Debug("Getting next TCert...done!")

	return rawCert, nil
}
Esempio n. 29
0
func (se *stateEncryptorImpl) Encrypt(msg []byte) ([]byte, error) {
	var b = make([]byte, 8)
	binary.BigEndian.PutUint64(b, se.counter)

	se.log.Debug("Encrypting with counter [%s].", utils.EncodeBase64(b))
	//	se.log.Info("Encrypting with txNonce  ", utils.EncodeBase64(se.txNonce))

	nonce := utils.HMACTruncated(se.nonceStateKey, b, se.nonceSize)

	se.counter++

	// Seal will append the output to the first argument; the usage
	// here appends the ciphertext to the nonce. The final parameter
	// is any additional data to be authenticated.
	out := se.gcmEnc.Seal(nonce, nonce, msg, se.invokeTxNonce)

	return append(se.invokeTxNonce, out...), nil
}
Esempio n. 30
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
}