fa8a3429e485de8c16a232c99984f9264984ec9e
[platform/upstream/connectedhomeip.git] / src / lib / protocols / fabric-provisioning / FabricProvisioning.h
1 /*
2  *
3  *    Copyright (c) 2020 Project CHIP Authors
4  *    Copyright (c) 2013-2017 Nest Labs, Inc.
5  *    All rights reserved.
6  *
7  *    Licensed under the Apache License, Version 2.0 (the "License");
8  *    you may not use this file except in compliance with the License.
9  *    You may obtain a copy of the License at
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *    Unless required by applicable law or agreed to in writing, software
14  *    distributed under the License is distributed on an "AS IS" BASIS,
15  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *    See the License for the specific language governing permissions and
17  *    limitations under the License.
18  */
19
20 /**
21  *    @file
22  *      This file defines the Fabric Provisioning Profile, used to
23  *      manage membership to CHIP Fabrics.
24  *
25  *      The Fabric Provisioning Profile facilitates client-server operations
26  *      such that the client (the controlling device) can trigger specific
27  *      functionality on the server (the device undergoing provisioning),
28  *      to allow it to create, join, and leave CHIP Fabrics.  This includes
29  *      communicating Fabric configuration information such as identifiers,
30  *      keys, security schemes, and related data.
31  */
32
33 #ifndef FABRICPROVISIONING_H_
34 #define FABRICPROVISIONING_H_
35
36 #include <core/CHIPCore.h>
37 #include <core/CHIPEncoding.h>
38 #include <core/CHIPTLV.h>
39 #include <message/CHIPServerBase.h>
40 #include <support/DLLUtil.h>
41
42 /**
43  *   @namespace chip::Protocols::FabricProvisioning
44  *
45  *   @brief
46  *     This namespace includes all interfaces within CHIP for the
47  *     CHIP Fabric Provisioning profile, the second of the three
48  *     CHIP provisioning profiles.
49  */
50
51 namespace chip {
52 namespace Protocols {
53 namespace FabricProvisioning {
54
55 using Inet::IPAddress;
56
57 /**
58  * Fabric Provisioning Status Codes
59  */
60 enum
61 {
62     kStatusCode_AlreadyMemberOfFabric = 1, /**< The recipient is already a member of a fabric. */
63     kStatusCode_NotMemberOfFabric     = 2, /**< The recipient is not a member of a fabric. */
64     kStatusCode_InvalidFabricConfig   = 3  /**< The specified fabric configuration was invalid. */
65 };
66
67 /**
68  * Fabric Provisioning Message Types
69  */
70 enum
71 {
72     // Application/Device Messages
73     kMsgType_CreateFabric            = 1,
74     kMsgType_LeaveFabric             = 2,
75     kMsgType_GetFabricConfig         = 3,
76     kMsgType_GetFabricConfigComplete = 4,
77     kMsgType_JoinExistingFabric      = 5
78 };
79
80 /**
81  * Fabric Provisioning Data Element Tags
82  */
83 enum
84 {
85     // ---- Top-level Data Elements ----
86     kTag_FabricConfig = 1, /**< [ structure ] Contains provisioning information for an existing fabric.
87                                   IMPORTANT NOTE: As a convenience to readers, all elements in a FabricConfig
88                                   must be encoded in numeric tag order, at all levels. */
89
90     // ---- Context-specific Tags for FabricConfig Structure ----
91     kTag_FabricId   = 1, /**< [ uint ] Fabric ID. */
92     kTag_FabricKeys = 2, /**< [ array ] List of FabricKey structures. */
93
94     // ---- Context-specific Tags for FabricKey Structure ----
95     kTag_FabricKeyId    = 1,       /**< [ uint ] CHIP key ID for fabric key. */
96     kTag_EncryptionType = 2,       /**< [ uint ] CHIP encryption type supported by the key. */
97     kTag_DataKey        = 3,       /**< [ byte-string ] Data encryption key. */
98     kTag_IntegrityKey   = 4,       /**< [ byte-string ] Data integrity key. */
99     kTag_KeyScope       = 5,       /**< [ uint ] Enumerated value identifying the category of devices that can possess
100                                                  the fabric key. */
101     kTag_RotationScheme    = 6,    /**< [ uint ] Enumerated value identifying the rotation scheme for the key. */
102     kTag_RemainingLifeTime = 7,    /**< [ uint ] Remaining time (in seconds) until key expiration. Absent if lifetime
103                                                  is indefinite or doesn't apply. */
104     kTag_RemainingReservedTime = 8 /**< [ uint ] Remaining time (in seconds) until key is eligible for use. Absent if
105                                                  key can be used right away. */
106 };
107
108 /**
109  * Delegate class for implementing additional actions corresponding to Fabric Provisioning operations.
110  */
111 class FabricProvisioningDelegate : public ChipServerDelegateBase
112 {
113 public:
114     /**
115      * Indicates that the device has created a new Fabric.
116      *
117      * @retval #CHIP_NO_ERROR On success.
118      * @retval other           Other CHIP or platform-specific error codes indicating that an error
119      *                         occurred preventing the device from creating a fabric.
120      */
121     virtual CHIP_ERROR HandleCreateFabric() = 0;
122
123     /**
124      * Indicates that the device has joined an existing Fabric.
125      *
126      * @retval #CHIP_NO_ERROR On success.
127      * @retval other           Other CHIP or platform-specific error codes indicating that an error
128      *                         occurred preventing the device from joining the fabric.
129      */
130     virtual CHIP_ERROR HandleJoinExistingFabric() = 0;
131
132     /**
133      * Indicates that the device has left a Fabric.
134      *
135      * @retval #CHIP_NO_ERROR On success.
136      * @retval other           Other CHIP or platform-specific error codes indicating that an error
137      *                         occurred preventing the device from leaving the fabric.
138      */
139     virtual CHIP_ERROR HandleLeaveFabric() = 0;
140
141     /**
142      * Indicates that the configuration of the current CHIP Fabric has been
143      * requested.
144      *
145      * @retval #CHIP_NO_ERROR On success.
146      * @retval other           Other CHIP or platform-specific error codes indicating that an error
147      *                         occurred preventing the device from returning the fabric config.
148      */
149     virtual CHIP_ERROR HandleGetFabricConfig() = 0;
150
151     /**
152      * Enforce message-level access control for an incoming Fabric Provisioning request message.
153      *
154      * @param[in] ec            The ExchangeContext over which the message was received.
155      * @param[in] msgProfileId  The profile id of the received message.
156      * @param[in] msgType       The message type of the received message.
157      * @param[in] msgInfo       A ChipMessageInfo structure containing information about the received message.
158      * @param[inout] result     An enumerated value describing the result of access control policy evaluation for
159      *                          the received message. Upon entry to the method, the value represents the tentative
160      *                          result at the current point in the evaluation process.  Upon return, the result
161      *                          is expected to represent the final assessment of access control policy for the
162      *                          message.
163      */
164     void EnforceAccessControl(ExchangeContext * ec, uint32_t msgProfileId, uint8_t msgType, const ChipMessageInfo * msgInfo,
165                               AccessControlResult & result) override;
166
167     /**
168      * Called to determine if the device is currently paired to an account.
169      */
170     // TODO: make this pure virtual when product code provides appropriate implementations.
171     virtual bool IsPairedToAccount() const;
172 };
173
174 /**
175  * Server class for implementing the Fabric Provisioning profile.
176  */
177 // TODO: Additional documentation detail required (i.e. expected class usage, number in the system, instantiation requirements,
178 // lifetime).
179 class DLL_EXPORT FabricProvisioningServer : public ChipServerBase
180 {
181 public:
182     FabricProvisioningServer();
183     FabricProvisioningServer(const FabricProvisioningServer &) = delete;
184     FabricProvisioningServer & operator=(const FabricProvisioningServer &) = delete;
185
186     CHIP_ERROR Init(ChipExchangeManager * exchangeMgr);
187     CHIP_ERROR Shutdown();
188
189     void SetDelegate(FabricProvisioningDelegate * delegate);
190
191     // Check if the session is marked as privileged to retrieve fabric config information.
192     bool SessionHasFabricConfigAccessPrivilege(uint16_t keyId, uint64_t peerNodeId) const;
193
194     virtual CHIP_ERROR SendSuccessResponse();
195     virtual CHIP_ERROR SendStatusReport(uint32_t statusProfileId, uint16_t statusCode, CHIP_ERROR sysError = CHIP_NO_ERROR);
196
197 protected:
198     FabricProvisioningDelegate * mDelegate;
199     ExchangeContext * mCurClientOp;
200
201 private:
202     static void HandleClientRequest(ExchangeContext * ec, const Inet::IPPacketInfo * pktInfo, const ChipMessageInfo * msgInfo,
203                                     uint32_t profileId, uint8_t msgType, PacketBuffer * payload);
204
205     // Utility functions for managing registration with/notification from ChipFabricState
206     // about whether the current security session is privileged to
207     // access fabric config information.
208     void GrantFabricConfigAccessPrivilege(uint16_t keyId, uint64_t peerNodeId);
209     void ClearFabricConfigAccessPrivilege();
210     static void HandleSessionEnd(uint16_t keyId, uint64_t peerNodeId, void * context);
211     CHIP_ERROR RegisterSessionEndCallbackWithFabricState();
212
213     // Indicates the session that is privileged to
214     // retrieve fabric config information.
215     struct FabricConfigAccessSession
216     {
217         uint64_t PeerNodeId;
218         uint16_t SessionKeyId;
219     };
220     FabricConfigAccessSession mFabricConfigAccessSession;
221
222     chip::ChipFabricState::SessionEndCbCtxt mSessionEndCbCtxt;
223 };
224
225 } // namespace FabricProvisioning
226 } // namespace Protocols
227 } // namespace chip
228
229 #endif /* FABRICPROVISIONING_H_ */