Hyperledger Fabric permission policy and access control

Hyperledger Fabric permission policy and access control

Access control is a very important function of the blockchain network. It is responsible for controlling whether an identity is allowed to take a certain operation (such as reading and writing a certain resource) in a certain scenario.

Common access control models include mandatory access control (Mandatory Access Control), discretionary access control (Discretionary Access Control), role-based access control (Role Based Access Control) and attribute-based access control (Attribute Based Access Control). The more powerful the model, the more complex it tends to be to implement.

Fabric implements a role-based access control model through the permission policy and access control list (ACL) mechanism, which can meet the needs of multiple scenarios such as resource access in the channel, endorsement control, or chaincode invocation control.

Application Scenario

Access scenarios include using different policies (such as channel policies, node policies, endorsement policies, etc.), and restricting specific operations on a resource according to access control lists (such as requiring identities to be Admins, Writers, etc.).


identity certificate

The basis for implementing permission policies is identity, and the realization of identity depends on the certificate mechanism. Through PKI-based membership management, the Fabric network can restrict resources in the network and various capabilities of access users.

Three types of certificates were considered in the initial design of Fabric: Enrollment Certificate, Transaction Certificate, and TLS certificate to ensure the security of communication links. The default signature algorithm of the certificate is ECDSA, and the hash algorithm is SHA-256.

●Enrollment certificate (ECert): Issued to entities such as users or nodes that provide registration credentials, representing the identity in the network. Can be effective for a long time.

●Transaction certificate (TCert): Issued to users to control the authority of each transaction, which can be different for different transactions to achieve anonymity and short-term validity. Not implemented yet.

● Communication certificate (TLSCert): Control access to the network layer, and can verify the identity of the remote entity to prevent eavesdropping. Can be effective for a long time.

At present, in terms of implementation, the identity of the entity is mainly verified through ECert, and the authority management is realized by checking the signature. The TCert function has not yet been implemented, and users can use the idemix mechanism to achieve partial anonymity.


identity collection

Based on the certificate mechanism, Fabric designed the identity collection (MSPPrincipal) to flexibly mark a group of individuals with specific identities.

The corresponding MSPPrincipal data structure:

The identity collection supports the classification of identities from the following different dimensions.

●Role: Distinguish according to the role of the certificate, such as Member, Admin, Client, Peer, Orderer, etc.

●OrganizationUnit: It is distinguished according to the OU information specified in the identity card.

●Identity: specify the certificate of an individual, and only if it matches completely can it be considered legal.

●Anonymity: Whether the certificate is anonymous, used for idemix-type MSP.

●Combined: It is composed of multiple other sub-identity sets, and it needs to meet all the sub-sets to be considered legal.

Individuals who meet a certain identity can be flexibly specified based on different dimensions, for example, a specific role (such as member or administrator) of a certain MSP, or a specific unit (OrganizationUnit) of a certain MSP, of course, can also be specified as a specific individual.

Note that different roles are currently being recognized in different ways. For the administrator role, the list of certificates under the local msp/admincerts path or certificates with OU information representing the administrator role will be recognized; roles such as Client, Peer, and Orderer need to check whether the certificate has the corresponding OU domain; for member roles , the certificate needs to be issued by the root certificate of the corresponding organization.


Implementation of Permissions Policy

A permissions policy specifies the set of identities that can perform an action. Taking channel-related strategies as an example, it generally includes read operations (such as obtaining channel transactions, blocks and other data), write operations (such as initiating transactions to channels), management operations (such as joining channels, modifying channel configuration information), etc. Perform permission restrictions. Modifications to the policy configuration itself are implemented through an additionally specified modification policy (mod_policy).

When an operator initiates an operation, the signature combination in the request is only allowed to execute if it satisfies the identity rules specified by the policy. In terms of implementation, each policy structure must implement the Policy interface. For a given set of signed data or identities, check according to the given rules to see if they meet the agreed conditions. If it matches, it means that the policy is satisfied; otherwise, it rejects it.

data structure

Policy-related data structures are defined in the common/policies.pb.go file of the fabric-protos-go project, which mainly includes three data structures: Policy, SignaturePolicyEnvelope (embedded SignaturePolicy structure) and ImplicitMetaPolicy, as shown in Figure 14-20 .

Among them, the value of Type represents the type of strategy, and the specific meaning is:

●UNKNOWN, reserved value, used for initialization.

● SIGNATURE, by matching signature-based combinations, such as at least three signatures in a certain MSP.

● MSP, which means that the policy must match the specified identity under a certain MSP, such as the administrator identity of the MSP.

●IMPLICIT_META, an implicit type, includes several sub-strategies, and specifies specific rules through Rule, including ANY, ALL, and MAJORITY, which are only used to mark channel rules in channel configuration.

The currently supported policy types mainly include SIGNATURE policy and IMPLICIT_META policy.

SIGNATUREStrategy

The SIGNATURE policy specifies that data be authenticated by signing, e.g., the combination of signatures that must satisfy a given identity

Among them, the SignaturePolicy structure represents a policy rule (rule). Support specifying a specific signature, or satisfying several (NOutOf) in a given policy set. The usage of NOutOf is very flexible. Based on it, arbitrarily complex policy semantics can be constructed recursively, and the AND and or combination relationship of multiple signature rules can be specified.

The SignaturePolicyEnvelope structure represents a complete policy, including the version number (version), policy rules (rule) and the set of identities associated with the policy (identities).

For example, if a certain policy requires the signature of the MP1 identity set, or the simultaneous signature of the MP2 set and the MP3 set, it can be expressed as MP1||(MP2&&MP3). The corresponding policy structure is as follows:

SignaturePolicyEnvelope{
    version: 0,
    rule: SignaturePolicy{
        n_out_of: NOutOf{
            N: 1,
            rules: [
                SignaturePolicy{ signed_by: 0 },
                SignaturePolicy{
                    n_out_of: NOutOf{
                        N: 2,
                        rules: [
                            SignaturePolicy{ signed_by: 1 },
                            SignaturePolicy{ signed_by: 2 },
                        ],
                    },
                },
            ],
        },
    },
    identities: [MP1, MP2, MP3] // 身份集合列表
}
// github.com/hyperledger/fabric-protos-go/common/policies.pb.go
type ImplicitMetaPolicy struct {
    SubPolicy string // 子策略类型名称,如 Readers、Writers、Admins
    Rule ImplicitMetaPolicy_Rule // 子策略的匹配条件,可以为 ANY、ALL、MAJORITY
}
ImplicitMetaPolicy{
    sub_policy: "Readers",
    rule: ANY,
}

Note that the matching process for signature policies is order sensitive (see FAB-4749). When performing a policy check, the given multiple signatures will be matched with the identity set in sequence according to the policy order. Once the signature is matched, it will be consumed and the next signature will be checked. For example, in the above example, if MP1 represents the administrator of organization A, MP2 represents the member of organization B, and MP3 represents the administrator of organization B, then for the signature combination [S1={administrator of organization B}, S2={organization B’s member}], will not match successfully. Because, S1 will be consumed after matching MP2, and the remaining S2 will fail when matching MP3. In order to avoid this situation, signatures with lower priority should be placed first when signing. For example, signatures representing membership should be placed before administrators. At the same time, for the identity collection list of the policy, the one with high priority should be put in front.


IMPLICIT_META strategy

The IMPLICIT_META policy is used for channel configuration, and it does not perform signature checking directly, but by referring to other sub-policies (eventually through the SIGNATURE policy). Inspection results are constrained by policy rules.


channel policy

One of the main application scenarios for permission policies is channel policies. The channel strategy adopts a hierarchical tree structure, the top layer is the /Channel group, and the bottom is the subgroups at all levels. A policy can be specified at each level as the default policy for that level.

Channel configuration can include different elements such as alliance group (only for system channels, including alliance organization information), application group (generally only for application channels, including organization information using channels), and sorting group (including sorting organization information).

A typical application channel example is shown in Figure 14-23, including a sorting group and an application group.

By default, policies within a channel use roles defined as follows:

# 通道全局策略
/Channel/Readers: ImplicitMetaPolicy-ANY Readers
/Channel/Writers: ImplicitMetaPolicy-ANY Writers
/Channel/Admins : ImplicitMetaPolicy-MAJORITY Admins
# 通道内应用组默认策略(仅当应用通道),需要从应用组织中推断
/Channel/Application/Readers: ImplicitMetaPolicy-ANY Readers
/Channel/Application/Writers: ImplicitMetaPolicy-ANY Writers
/Channel/Application/Admins : ImplicitMetaPolicy-MAJORITY Admins
/Channel/Application/Endorsement: ImplicitMetaPolicy-MAJORITY Endorsement
/Channel/Application/LifecycleEndorsement: ImplicitMetaPolicy-MAJORITY 
LifecycleEndorsement
# 通道内应用组各组织的默认策略(仅当应用通道)
/Channel/Application/Org/Readers: SignaturePolicy for 1 of Org Member
/Channel/Application/Org/Writers: SignaturePolicy for 1 of Org Member
/Channel/Application/Org/Admins : SignaturePolicy for 1 of Org Admin
/Channel/Application/Org/Endorsement: SignaturePolicy for 1 of Org Member
# 通道内排序组的默认策略,需要从排序组织中推断
/Channel/Orderer/Readers: ImplicitMetaPolicy-ANY Readers
/Channel/Orderer/Writers: ImplicitMetaPolicy-ANY Writers
/Channel/Orderer/Admins : ImplicitMetaPolicy-MAJORITY Admins
/Channel/Orderer/BlockValidation: ImplicitMetaPolicy-ANY Writers
# 通道内排序组中各组织的默认策略
/Channel/Orderer/Org/Readers: SignaturePolicy for 1 of Org Member
/Channel/Orderer/Org/Writers: SignaturePolicy for 1 of Org Member
/Channel/Orderer/Org/Admins : SignaturePolicy for 1 of Org Admin
# 通道内联盟组的默认策略(仅当系统通道)
/Channel/Consortiums/Admins: SignaturePolicy for ANY
# 通道内联盟组中某联盟的默认通道创建策略(仅当系统通道)
/Channel/Consortiums/Consortium/ChannelCreationPolicy: ImplicitMetaPolicy-ANY 
for Admin
# 通道内联盟组中某联盟组织的默认策略(仅当系统通道)
/Channel/Consortiums/Consortium/Org/Readers: SignaturePolicy for 1 of Org Member: 
 ImplicitMetaPolicy-ANY for Admin
/Channel/Consortiums/Consortium/Org/Writers: SignaturePolicy for 1 of Org Member
/Channel/Consortiums/Consortium/Org/Admins : SignaturePolicy for 1 of Org Admin

Among them, the default policy (mod_policy) for modifying the elements in the channel is Admins; the modification policy for configuration related to sorting is specified as /Channel/Orderer/Admins, mainly including related configurations in the system channel, such as Orderer-Addresses , Consortiums and specific consortium configurations.

In addition, the policy of the application channel will consider the Orderer group and the Application group in the latest configuration; the policy of the system channel will consider the Orderer group and the Consortiums group in the latest configuration. When creating a new application channel, the user needs to specify the Application group configuration. If the Orderer group configuration is not specified, it will be automatically inherited from the system channel.


channel access control

Currently, most access permissions in Fabric are specified through channel access control lists. Access control lists are located in the channel configuration and are recognized by all members of the channel. It can be specified by using config igtx.yaml when creating a new channel, or it can be changed later by configuration update. An example of an ACL configuration is as follows, including the ACL and its referenced policies:

Application: &ApplicationDefaults
    ACLs: &ACLsDefault
        # Lifecycle 方法调用权限:CheckCommitReadiness()、CommitChaincodeDefinition()、 
QueryChaincodeDefinition()、QueryChaincodeDefinitions()
        _lifecycle/CheckCommitReadiness: /Channel/Application/Writers
        _lifecycle/CommitChaincodeDefinition: /Channel/Application/Writers
        _lifecycle/QueryChaincodeDefinition: /Channel/Application/Readers
        _lifecycle/QueryChaincodeDefinitions: /Channel/Application/Readers
        # LSCC 方法调用权限:getid()、getdepspec()、getccdata()、getchaincodes()
        lscc/ChaincodeExists: /Channel/Application/Readers
lscc/GetDeploymentSpec: /Channel/Application/Readers
        lscc/GetChaincodeData: /Channel/Application/Readers
        lscc/GetInstantiatedChaincodes: /Channel/Application/Readers
        # QSCC 方法调用权限:GetChainInfo()、GetBlockByNumber()、GetBlockByHash()、
GetTransactionByID()、GetBlockByTxID()
        qscc/GetChainInfo: /Channel/Application/Readers
        qscc/GetBlockByNumber: /Channel/Application/Readers
        qscc/GetBlockByHash: /Channel/Application/Readers
        qscc/GetTransactionByID: /Channel/Application/Readers
        qscc/GetBlockByTxID: /Channel/Application/Readers
        # CSCC 方法调用权限:GetConfigBlock()
        cscc/GetConfigBlock: /Channel/Application/Readers
        # 通道内链码调用权限(向 Peer 发送背书请求)
        peer/Propose: /Channel/Application/Writers
        # 通道内跨链码调用权限
        peer/ChaincodeToChaincode: /Channel/Application/Readers
        # 接收区块事件权限
        event/Block: /Channel/Application/Readers
        # 接收过滤区块事件权限
        event/FilteredBlock: /Channel/Application/Readers
    # 默认应用通道内组织成员为空
    Organizations:
    # 通道内相关的策略,可被 ACL 中引用,用户也可以自定义全局策略
    Policies: &ApplicationDefaultPolicies
        Readers:
            Type: ImplicitMeta
            Rule: "ANY Readers"
        Writers:
            Type: ImplicitMeta
            Rule: "ANY Writers"
        Admins:
            Type: ImplicitMeta
            Rule: "MAJORITY Admins"
    # 引用应用通道默认的能力集合
    Capabilities:
        <<: *ApplicationCapabilities

The resource access permissions supported by the current channel configuration are summarized in the following table:

resource access permissions Function
Lifecycle/InstallChaincode Book MSP Admins Install chaincode
Lifecycle/QueryInstalledChaincode Book MSP Admins Query installed chaincode information
Lifecycle/GetInstalledChaincodePackage Book MSP Admins Get the chaincode installation package
Lifecycle/QueryInstalledChaincodes Book MSP Admins Query the list of all installed chaincodes
Lifecycle/ApproveChaincodeDefinitionForMyOrg Book MSP Admins Book MSP Admins
Lifecycle/CommitChaincodeDefinition Channel Writers Commit the chaincode definition
Lifecycle/QueryChaincodeDefinition Channel Writers Query the specified committed chaincode definition
Lifecycle/CheckCommitReadiness Channel Writers Check chaincode definition commit status
Lscc/Install Book MSP Admins Traditionally install chaincode
Lscc/GetInstalledChaincodes Book MSP Admins Traditionally get the list of installed chaincodes
Lscc/Deploy Channel Writers Traditional instantiated chaincode
Lscc/Upgrade Channel Writers Traditional upgrade chaincode
Lscc/ChaincodeExists Channel Readers Check if the chaincode is installed
Lscc/GetDeploymentSpec Channel Readers Get the installation package
Lscc/GetChaincodeData Channel Readers Get the complete data package of the chaincode
Lscc/GetInstantiatedChaincodes Channel Readers Get the list of instantiated chaincodes
Lscc/GetCollectionsConfig Channel Readers Get private data collection configuration
Qscc/GetChainInfo Channel Readers Query channel information
Qscc/GetBlockByNumber Channel Readers Get the specified serial number block
Qscc/GetBlockByHash Channel Readers Get the specified hash block
Qscc/GetTransactionByID Channel Readers Get the specified ID transaction
Qscc/GetBlockByTxID Channel Readers Get the block including the specified transaction
Qscc/JoinChain Channel Readers join channel
Qscc/GetChannels Channel Readers Get the list of joined channels
Qscc/GetConfigBlock Channel Readers Get configuration block
Peer/Propose Channel Writers call chaincode
Peer/ChaincodeToChaincode Channel Writers Cross chain code call
Event/Block Channel Readers Listen for full block events
Event/FilteredBlock Channel Readers Listen to filter block events

Endorsement policy

Chaincode endorsement policy

When the user approves the execution of the chain code (the instantiated chain code before version 2.0), he can specify the endorsement policy (Endorsement Policy) that needs to be met when calling the chain code and store it in the chain code definition. When a chaincode call transaction is submitted, Peer will check whether the transaction carries signature information that meets the specified endorsement policy.

The endorsement policy can be specified in two ways, SignaturePolicy or ChannelConfigPolicy, to build a very flexible policy combination. The SignaturePolicy method specifies the use of a specific identity signature combination for endorsement. For example, specify any membership in certain organizations for endorsement, or at least one administrator identity for endorsement, etc.

Syntactically, the endorsement policy specifies which SignaturePolicies are required through -P; specifies the number of Signature-Policy required through -T. At present, the client has realized preliminary support for the endorsement policy, and the set of identity roles (including admin, member, peer, and client) combined by AND, OR, and OutOf can be specified through -P.

The following policy specifies that either the administrator of Org1 endorses, or the peer nodes of Org2 and Org3 endorse simultaneously:

OR('Org1.admin', AND('Org2.peer', 'Org3.peer'))

The following policy specifies endorsement by members of at least two of the three organizations:

OutOf(2, 'Org1.member', 'Org2.member', 'Org3.member')

The ChannelConfigPolicy method refers to the existing policy name in the channel configuration, and uses the corresponding identity for endorsement.

For example, if you do not explicitly specify an endorsement policy, the Channel/Application/Endorsement policy in the channel configuration will be used, which defaults to the majority of members in the channel.


Key value endorsement strategy

In addition to endorsement policies for chaincodes (all states of the chaincode), since version 1.3.0, Fabric supports more fine-grained endorsement policies based on specific states (key values). Users can specify the endorsement policy required to modify a specified state.

Include the following shim layer APIs, which can be used in chaincode.

●GetStateValidationParameter(collection,key string)([]byte,error): Get the endorsement policy of the specified collection for the specified key value.

●SetStateValidationParameter(collection,key string,ep[]byte)error: specifies the endorsement policy bound to a certain key value.

●GetPrivateDataValidationParameter(collection,key string)([]byte,error): Get the endorsement policy of the specified collection for the specified private key value.

●SetPrivateDataValidationParameter(collection, key string, ep[]byte) error: Specify the endorsement policy corresponding to a private key value.

Peer will check the endorsement policy during the block submission phase.


Private Data Collection Endorsement Policy

Since version 2.0, users can also specify the corresponding endorsement policy for each private data set. When the user writes or modifies the key value in the private data set, the specified endorsement policy needs to be met. At this time, the overall endorsement policy of the chaincode will be ignored. The user who initiates the write request does not have to be a member of the private data collection. Using the private data collection endorsement policy can restrict the write operation of private data and achieve more secure chain code access protection.

Similar to the chaincode endorsement policy, the private data collection endorsement policy supports SignaturePolicy or ChannelConfigPolicy. For example, you can specify the signaturePolicy or channelConfig-Policy endorsement policy in the collection configuration file collection.json. The sample code is as follows:

[
 {
     "name": "collection1",       // 集合名称
     "policy": "OR('Org1MSP.member', 'Org2MSP.member')", // 集合成员
     "requiredPeerCount": 1, // 背书之前至少扩散私密数据到的节点数
     "maxPeerCount": 3,      // 背书之前尝试扩散最多节点个数,不能小于 requiredPeerCount
     "blockToLive":99999,    // 私密数据保存时长。0 意味着永不过期
     "memberOnlyRead": true, // 是否只允许集合成员(如客户端)来读取私密数据,v1.4 开始支持
     "memberOnlyWrite": true,// 是否只允许集合成员(如客户端)来发起对私密数据的写交易,v2.0  
         // 开始支持
     "endorsementPolicy": {  // 指定对私密数据进行写操作时的背书策略,会取代链码的背书策略
      "signaturePolicy": "OR('Org1MSP.member')" // 指定使用签名策略
    }
},
{
     "name": "collection2",
     "policy": "OR('Org1MSP.member')",
     "requiredPeerCount": 1,
     "maxPeerCount": 3,
     "blockToLive":3,
     "memberOnlyRead": true,
     "memberOnlyWrite": true,
     "endorsementPolicy": {
      "channelConfigPolicy": "Channel/Application/Writers" // 指定使用通道配置内已 
              // 有策略
    }
}
]

Chaincode access control based on certificate attributes

In addition, users can also implement custom control logic in their chaincode through chaincode access control based on certificate attributes. For example, the identity certificate of the caller can be detected at the entrance of the method, and some specific identity callers can be filtered to achieve fine-grained control based on key values ​​or other conditions.

// github.com/hyperledger/fabric-chaincode-go/pkg/cid/cid.go
// 获取根据证书主题生成的唯一标识
func GetID() (string, error) 
// 获取 MSP ID
func GetMSPID() (string, error) 
// 获取证书某个属性的值
func GetAttributeValue(attrName string) (value string, found bool, err error)
// 检查证书中某个属性是给定值
func AssertAttributeValue(attrName, attrValue string) error 
// 获取调用者的 X509 证书
func GetX509Certificate() (*x509.Certificate, error)
// 判断调用者是否属于给定 OU
func HasOUValue(stub ChaincodeStubInterface, OUValue string) (bool, error)

Users can use these methods to implement access control over the identity of the caller in the chaincode method.

For example, set the custom attribute "abac."+role in the extension field of the certificate, and determine in the chaincode method that only users whose certificates have this attribute can call this method. The sample code is as follows:

import "github.com/hyperledger/fabric-chaincode-go/pkg/cid"
 func (t *TestChaincode) Access(stub shim.ChaincodeStubInterface, role string)  
    pb.Response {
    // 根据属性值来判断是否允许访问方法
    err := cid.AssertAttributeValue(stub, "abac."+role, "true")
    if err != nil {
        return shim.Error("Not allowed with missed attribution"+err.Error())
    }
    ...
}

instantiation strategy

The instantiation policy (Instantiation Policy) is only effective before version 2.0, and is responsible for controlling the instantiation of the chaincode. Committer uses VSCC in the confirmation phase to check the permissions of chaincode deployment operations in the network.

Currently, the instantiation policy is also specified using the SignaturePolicy structure, which can build complex signature verification combinations based on the identity collection structure.

By default, the current MSP administrator identity is used as the default policy, that is, only the current MSP administrator can instantiate the chaincode. This can prevent the chaincode from being instantiated in other channels by other organization members in the channel without permission.

The check of the instantiated policy occurs during the Peer's endorsement phase.

Guess you like

Origin blog.csdn.net/weixin_45839894/article/details/123449967