1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 #include "pw_bluetooth_sapphire/internal/host/att/permissions.h"
16
17 namespace bt::att {
18 namespace {
19
CheckSecurity(const AccessRequirements & reqs,const sm::SecurityProperties & security)20 fit::result<ErrorCode> CheckSecurity(const AccessRequirements& reqs,
21 const sm::SecurityProperties& security) {
22 if (reqs.encryption_required() &&
23 security.level() < sm::SecurityLevel::kEncrypted) {
24 // If the peer is bonded but the link is not encrypted the "Insufficient
25 // Encryption" error should be sent. Our GAP layer always keeps the link
26 // encrypted so the authentication procedure needs to fail during
27 // connection. We don't distinguish this from the un-paired state.
28 // (NOTE: It is possible for the link to be authenticated without encryption
29 // in LE Security Mode 2, which we do not support).
30 return fit::error(ErrorCode::kInsufficientAuthentication);
31 }
32
33 if ((reqs.authentication_required() || reqs.authorization_required()) &&
34 security.level() < sm::SecurityLevel::kAuthenticated) {
35 return fit::error(ErrorCode::kInsufficientAuthentication);
36 }
37
38 if (reqs.encryption_required() &&
39 security.enc_key_size() < reqs.min_enc_key_size()) {
40 return fit::error(ErrorCode::kInsufficientEncryptionKeySize);
41 }
42
43 return fit::ok();
44 }
45
46 } // namespace
47
CheckReadPermissions(const AccessRequirements & reqs,const sm::SecurityProperties & security)48 fit::result<ErrorCode> CheckReadPermissions(
49 const AccessRequirements& reqs, const sm::SecurityProperties& security) {
50 if (!reqs.allowed()) {
51 return fit::error(ErrorCode::kReadNotPermitted);
52 }
53 return CheckSecurity(reqs, security);
54 }
55
CheckWritePermissions(const AccessRequirements & reqs,const sm::SecurityProperties & security)56 fit::result<ErrorCode> CheckWritePermissions(
57 const AccessRequirements& reqs, const sm::SecurityProperties& security) {
58 if (!reqs.allowed()) {
59 return fit::error(ErrorCode::kWriteNotPermitted);
60 }
61 return CheckSecurity(reqs, security);
62 }
63
64 } // namespace bt::att
65