diff --git a/BUILD.gn b/BUILD.gn index 4e262743dd640165d7de1ea5031b9743cabd5a46..c26997082ee9aadebfd27f14ef8069a5bc248969 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -11,24 +11,50 @@ # See the License for the specific language governing permissions and # limitations under the License. +#import("//base/security/permission/permission.gni") import("//build/ohos.gni") -group("accesstoken_build_module_standard") { +group("accesstoken_build_module") { if (is_standard_system) { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", - "//base/security/access_token/services/accesstoken:accesstoken_manager_service", - "//base/security/access_token/services/accesstoken/main/sa_profile:accesstoken_sa_profile_standard", + "//base/security/access_token/interfaces/innerkits/atlib:libaccesstoken_lib", + "//base/security/access_token/services/accesstokenmanager:accesstoken_manager_service", + "//base/security/access_token/services/accesstokenmanager/main/sa_profile:accesstoken_sa_profile_standard", ] } } -group("accesstoken_build_module_standard_test") { +group("tokensync_build_module") { + if (is_standard_system) { + deps = [ + "//base/security/access_token/interfaces/innerkits/tokensync:libtokensync_sdk", + "//base/security/access_token/services/tokensyncmanager:tokensync_manager_service", + "//base/security/access_token/services/tokensyncmanager/main/sa_profile:tokensync_sa_profile_standard", + ] + } +} + +group("accesstoken_build_module_test") { testonly = true deps = [] if (is_standard_system) { deps += [ "//base/security/access_token/interfaces/innerkits/accesstoken/test:unittest", + "//base/security/access_token/interfaces/innerkits/atlib/test:unittest", + "//base/security/access_token/interfaces/innerkits/tokensync/test:unittest", + "//base/security/access_token/services/accesstokenmanager/test:unittest", ] } -} \ No newline at end of file +} + +#group("distributed_permission") { +# if (is_standard_system) { +# deps = [ +# "${distributed_permission_innerkits_distributed_path}:distributed_permission_innerkits", +# "${distributed_permission_record_database_path}:permission_standard_infrastructure_record_database", +# "${distributed_permission_services_path}:distributed_permission_services", +# "${distributed_permission_services_path}/main/sa_profile:distributed_permission_sa_profile_standard", +# ] +# } +#} diff --git a/README.md b/README.md index 9d2b06ed3c0a7d5bbad7b383686580f7721cc7c2..616187854ec4bc35be87be1272bca9061127f86c 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ - [接口说明](#section1551164914237) - [使用说明](#section129654513264) -- [相关仓](#section1371113476307) +- [相关仓](#section1371113476307) ## 简介 @@ -24,7 +24,7 @@ ATM模块主要提供如下功能: ## 目录 ``` -/base/security/access_token +/base/security/access_token ├── frameworks # 框架层,作为基础功能目录,被interfaces和services使用 │ ├── accesstoken # Accesstoken管理框架代码实现 │ ├── tokensync # Accesstoken信息同步框架代码实现 diff --git a/config/base/string.json b/config/base/string.json new file mode 100644 index 0000000000000000000000000000000000000000..cd352ad635d17f56e377954eaf91d337d035b4fe --- /dev/null +++ b/config/base/string.json @@ -0,0 +1,436 @@ +{ + "string": [ + { + "name": "ohos_id_text_font_family_regular", + "value": "sans-serif" + }, + { + "name": "ohos_id_text_font_family_medium", + "value": "HwChinese-medium" + }, + { + "name": "ohos_lab_answer_call", + "value": "Answer phone calls" + }, + { + "name": "ohos_desc_answer_call", + "value": "Allows an application to answer incoming calls." + }, + { + "name": "ohos_lab_internet", + "value": "Access Internet" + }, + { + "name": "ohos_desc_internet", + "value": "Allows an application to access the Internet." + }, + { + "name": "ohos_lab_modify_audio_settings", + "value": "Play audio" + }, + { + "name": "ohos_desc_modify_audio_settings", + "value": "Allows an application to enable or disable the audio playback channel." + }, + { + "name": "ohos_lab_read_calendar", + "value": "Read calendar information" + }, + { + "name": "ohos_desc_read_calendar", + "value": "Allows an application to read calendar information." + }, + { + "name": "ohos_lab_read_call_log", + "value": "Read call logs" + }, + { + "name": "ohos_desc_read_call_log", + "value": "Allows an application to read call logs." + }, + { + "name": "ohos_lab_read_cell_messages", + "value": "Read cell broadcast messages" + }, + { + "name": "ohos_desc_read_cell_messages", + "value": "Allows an application to read cell broadcast messages received by the device." + }, + { + "name": "ohos_lab_read_contacts", + "value": "Read Contacts" + }, + { + "name": "ohos_desc_read_contacts", + "value": "Allows an application to read Contacts." + }, + { + "name": "ohos_lab_get_telephony_state", + "value": "Read telephony information" + }, + { + "name": "ohos_desc_get_telephony_state", + "value": "Allows an application to access telephony information, including the phone number, device ID, voice mailbox, IMEI, and ICCID." + }, + { + "name": "ohos_lab_read_messages", + "value": "Read SMS/MMS messages" + }, + { + "name": "ohos_desc_read_messages", + "value": "Allows an application to read SMS/MMS messages." + }, + { + "name": "ohos_lab_receive_mms", + "value": "Receive MMS messages" + }, + { + "name": "ohos_desc_receive_mms", + "value": "Allows an application to receive MMS messages." + }, + { + "name": "ohos_lab_receive_sms", + "value": "Receive SMS messages" + }, + { + "name": "ohos_desc_receive_sms", + "value": "Allows an application to receive SMS messages." + }, + { + "name": "ohos_lab_receive_wap_messages", + "value": "Receive WAP messages" + }, + { + "name": "ohos_desc_receive_wap_messages", + "value": "Allows an application to receive WAP messages." + }, + { + "name": "ohos_lab_microphone", + "value": "Record audio" + }, + { + "name": "ohos_desc_microphone", + "value": "Allows an application to enable or disable the audio recording channel." + }, + { + "name": "ohos_lab_send_messages", + "value": "Send SMS/MMS messages" + }, + { + "name": "ohos_desc_send_messages", + "value": "Allows an application to send SMS/MMS messages." + }, + { + "name": "ohos_lab_write_calendar", + "value": "Add/Modify/Delete calendar events" + }, + { + "name": "ohos_desc_write_calendar", + "value": "Allows an application to add, modify, and delete calendar events." + }, + { + "name": "ohos_lab_write_call_log", + "value": "Add/Modify/Delete call logs" + }, + { + "name": "ohos_desc_write_call_log", + "value": "Allows an application to add, modify, and delete call logs." + }, + { + "name": "ohos_lab_write_contacts", + "value": "Add/Modify/Delete Contacts" + }, + { + "name": "ohos_desc_write_contacts", + "value": "Allows an application to add, modify, and delete Contacts." + }, + { + "name": "ohos_lab_distributed_datasync", + "value": "Obtain the device location" + }, + { + "name": "ohos_desc_distributed_datasync", + "value": "Allows a background application to obtain the device location." + }, + { + "name": "ohos_lab_manage_voicemail", + "value": "Manage the voice mailbox" + }, + { + "name": "ohos_desc_manage_voicemail", + "value": "Allows an application to manage the voice mailbox." + }, + { + "name": "ohos_lab_location_in_background", + "value": "Obtain the device location" + }, + { + "name": "ohos_desc_location_in_background", + "value": "Allows a background application to obtain the device location." + }, + { + "name": "ohos_lab_location", + "value": "Obtain the device location" + }, + { + "name": "ohos_desc_location", + "value": "Allows a foreground application to obtain the device location." + }, + { + "name": "ohos_lab_media_location", + "value": "Access location information" + }, + { + "name": "ohos_desc_media_location", + "value": "Allows an application to read the location where a photo is taken, such as the longitude and latitude." + }, + { + "name": "ohos_lab_get_network_info", + "value": "Read network information" + }, + { + "name": "ohos_desc_get_network_info", + "value": "Allows an application to obtain network information." + }, + { + "name": "ohos_lab_place_call", + "value": "Make calls" + }, + { + "name": "ohos_desc_place_call", + "value": "Allows an application to make calls without starting the dialer." + }, + { + "name": "ohos_lab_camera", + "value": "Take photos or shoot videos" + }, + { + "name": "ohos_desc_camera", + "value": "Allows an application to take photos and shoot videos." + }, + { + "name": "ohos_lab_set_network_info", + "value": "Set data network" + }, + { + "name": "ohos_desc_set_network_info", + "value": "Allows an application to set data network information." + }, + { + "name": "ohos_lab_read_media", + "value": "Read media files" + }, + { + "name": "ohos_desc_read_media", + "value": "Allows an application to read media files, such as video and audio clips and images." + }, + { + "name": "ohos_lab_write_media", + "value": "Read and write media files" + }, + { + "name": "ohos_desc_write_media", + "value": "Allows an application to read and write media files, such as video and audio clips and images." + }, + { + "name": "ohos_lab_distributed_virtualdevice", + "value": "Discover devices for multi-device collaboration" + }, + { + "name": "ohos_desc_distributed_virtualdevice", + "value": "Allows an application to discover and access other devices in multi-device collaboration." + }, + { + "name": "ohos_lab_enroll_biometric", + "value": "Manage biological features" + }, + { + "name": "ohos_desc_enroll_biometric", + "value": "Allows an application to manage biometrical features." + }, + { + "name": "ohos_lab_access_biometric", + "value": "Biometric feature authentication" + }, + { + "name": "ohos_desc_access_biometric", + "value": "Allows an application to use biometric features for authentication." + }, + { + "name": "ohos_lab_access_biometric_internal", + "value": "Biometric feature authentication for system applications" + }, + { + "name": "ohos_desc_access_biometric_internal", + "value": "Allows a system application to use biometric features for authentication." + }, + { + "name": "ohos_lab_reset_biometric_lockout", + "value": "Reset the upper limit for biometric feature authentication failures" + }, + { + "name": "ohos_desc_reset_biometric_lockout", + "value": "Allows an application to reset the maximum number of failures allowed before biometric feature authentication is locked." + }, + { + "name": "ohos_lab_set_time", + "value": "Set the system time" + }, + { + "name": "ohos_desc_set_time", + "value": "Allows an application to set the system time." + }, + { + "name": "ohos_lab_set_time_zone", + "value": "Set the system time zone" + }, + { + "name": "ohos_desc_set_time_zone", + "value": "Allows an application to set the system time zone." + }, + { + "name": "ohos_lab_download_session_manager", + "value": "Manage download sessions" + }, + { + "name": "ohos_desc_download_session_manager", + "value": "Allows an application to manage download sessions." + }, + { + "name": "ohos_lab_commonevent_sticky", + "value": "Sticky common events" + }, + { + "name": "ohos_desc_commonevent_sticky", + "value": "Allows an application to publish sticky common events." + }, + { + "name": "ohos_lab_manage_local_accounts", + "value": "Manage local accounts" + }, + { + "name": "ohos_desc_manage_local_accounts", + "value": "Allows an application to add, delete, modify, and query local accounts." + }, + { + "name": "ohos_lab_interact_across_local_accounts", + "value": "Multi-account mutual access" + }, + { + "name": "ohos_desc_interact_across_local_accounts", + "value": "Allows an application to access accounts of other applications." + }, + { + "name": "ohos_lab_vibrate", + "value": "Vibrate" + }, + { + "name": "ohos_desc_vibrate", + "value": "Allows an application to use the vibrator." + }, + { + "name": "ohos_lab_activity_motion", + "value": "Read workout status" + }, + { + "name": "ohos_desc_activity_motion", + "value": "Allows an application to read the workout status of the user." + }, + { + "name": "ohos_lab_read_health_data", + "value": "Read health data" + }, + { + "name": "ohos_desc_read_health_data", + "value": "Allows an application to read the health data of the user." + }, + { + "name": "ohos_lab_connect_ime_ability", + "value": "Bind to the input method framework" + }, + { + "name": "ohos_desc_connect_ime_ability", + "value": "Allows an application to be invoked by the input method framework." + }, + { + "name": "ohos_lab_set_wallpaper", + "value": "Set static wallpapers" + }, + { + "name": "ohos_desc_set_wallpaper", + "value": "Allows an application to set a static wallpaper." + }, + { + "name": "ohos_lab_get_wallpaper", + "value": "Read wallpaper files" + }, + { + "name": "ohos_desc_get_wallpaper", + "value": "Allows an application to read wallpaper files." + }, + { + "name": "ohos_lab_interact_across_local_accounts_extension", + "value": "Multi-account access extension" + }, + { + "name": "ohos_desc_interact_across_local_accounts_extension", + "value": "Allows an application to set the attributes of applications of other users." + }, + { + "name": "ohos_lab_accelerometer", + "value": "Read acceleration sensor data" + }, + { + "name": "ohos_desc_accelerometer", + "value": "Allows an application to read data from an acceleration sensor." + }, + { + "name": "ohos_lab_gyroscope", + "value": "Read gyroscope sensor data" + }, + { + "name": "ohos_desc_gyroscope", + "value": "Allows an application to read data from a gyroscope sensor." + }, + { + "name": "ohos_lab_set_telephony_state", + "value": "Set telephony state" + }, + { + "name": "ohos_desc_set_telephony_state", + "value": "Allows an application to set the telephony state, for example, to enable or disable the airplane mode, and change the network mode." + }, + { + "name": "ohos_lab_bundle_active_info", + "value": "Query application running time" + }, + { + "name": "ohos_desc_bundle_active_info", + "value": "Allows a system application or privileged application to obtain how long other applications have been running in the foreground or background." + }, + { + "name": "ohos_lab_publish_agent_reminder", + "value": "Agent-powered reminder" + }, + { + "name": "ohos_desc_publish_agent_reminder", + "value": "Allows an application to use agent-powered reminders." + }, + { + "name": "ohos_lab_control_task_sync_animator", + "value": "Sync task animation" + }, + { + "name": "ohos_desc_control_task_sync_animator", + "value": "Allows an application to use sync task animations." + }, + { + "name": "ohos_lab_notification_controller", + "value": "System interfaces" + }, + { + "name": "ohos_desc_notification_controller", + "value": "Allows an application to use notification management interfaces." + } + ] +} \ No newline at end of file diff --git a/config/config.json b/config/config.json new file mode 100644 index 0000000000000000000000000000000000000000..a3737ed9168c43ca6817a54ca9ce9d4a5c8bab70 --- /dev/null +++ b/config/config.json @@ -0,0 +1,770 @@ +{ + "app": { + "bundleName": "ohos.global.systemres", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0.0.1" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package": "ohos.global.systemres", + "deviceType": [ + "default", + "tv", + "car", + "wearable" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "entry", + "moduleType": "entry" + }, + "definePermissions": [ + { + "name": "ohos.permission.ANSWER_CALL", + "grantMode": "user_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_answer_call", + "description": "$string:ohos_desc_answer_call" + }, + { + "name": "ohos.permission.USE_BLUETOOTH", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.DISCOVER_BLUETOOTH", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.MANAGE_BLUETOOTH", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.INTERNET", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_internet", + "description": "$string:ohos_desc_internet" + }, + { + "name": "ohos.permission.MODIFY_AUDIO_SETTINGS", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_modify_audio_settings", + "description": "$string:ohos_desc_modify_audio_settings" + }, + { + "name": "ohos.permission.READ_CALENDAR", + "grantMode": "user_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_read_calendar", + "description": "$string:ohos_desc_read_calendar" + }, + { + "name": "ohos.permission.READ_CALL_LOG", + "grantMode": "user_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_read_call_log", + "description": "$string:ohos_desc_read_call_log" + }, + { + "name": "ohos.permission.READ_CELL_MESSAGES", + "grantMode": "user_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_read_cell_messages", + "description": "$string:ohos_desc_read_cell_messages" + }, + { + "name": "ohos.permission.READ_CONTACTS", + "grantMode": "user_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_read_contacts", + "description": "$string:ohos_desc_read_contacts" + }, + { + "name": "ohos.permission.GET_TELEPHONY_STATE", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_get_telephony_state", + "description": "$string:ohos_desc_get_telephony_state" + }, + { + "name": "ohos.permission.READ_MESSAGES", + "grantMode": "user_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_read_messages", + "description": "$string:ohos_desc_read_messages" + }, + { + "name": "ohos.permission.RECEIVE_MMS", + "grantMode": "user_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_receive_mms", + "description": "$string:ohos_desc_receive_mms" + }, + { + "name": "ohos.permission.RECEIVE_SMS", + "grantMode": "user_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_receive_sms", + "description": "$string:ohos_desc_receive_sms" + }, + { + "name": "ohos.permission.RECEIVE_WAP_MESSAGES", + "grantMode": "user_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_receive_wap_messages", + "description": "$string:ohos_desc_receive_wap_messages" + }, + { + "name": "ohos.permission.MICROPHONE", + "grantMode": "user_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_microphone", + "description": "$string:ohos_desc_microphone" + }, + { + "name": "ohos.permission.SEND_MESSAGES", + "grantMode": "user_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_send_messages", + "description": "$string:ohos_desc_send_messages" + }, + { + "name": "ohos.permission.WRITE_CALENDAR", + "grantMode": "user_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_write_calendar", + "description": "$string:ohos_desc_write_calendar" + }, + { + "name": "ohos.permission.WRITE_CALL_LOG", + "grantMode": "user_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_write_call_log", + "description": "$string:ohos_desc_write_call_log" + }, + { + "name": "ohos.permission.WRITE_CONTACTS", + "grantMode": "user_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_write_contacts", + "description": "$string:ohos_desc_write_contacts" + }, + { + "name": "ohos.permission.DISTRIBUTED_DATASYNC", + "grantMode": "user_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": true, + "label": "$string:ohos_lab_distributed_datasync", + "description": "$string:ohos_desc_distributed_datasync" + }, + { + "name": "ohos.permission.MANAGE_VOICEMAIL", + "grantMode": "user_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_manage_voicemail", + "description": "$string:ohos_desc_manage_voicemail" + }, + { + "name": "ohos.permission.REQUIRE_FORM", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.LOCATION_IN_BACKGROUND", + "grantMode": "user_grant", + "availableScope": "normal", + "provisionEnable": false, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_location_in_background", + "description": "$string:ohos_desc_location_in_background" + }, + { + "name": "ohos.permission.LOCATION", + "grantMode": "user_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": true, + "label": "$string:ohos_lab_location", + "description": "$string:ohos_desc_location" + }, + { + "name": "ohos.permission.MEDIA_LOCATION", + "grantMode": "user_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": true, + "label": "$string:ohos_lab_media_location", + "description": "$string:ohos_desc_media_location" + }, + { + "name": "ohos.permission.GET_NETWORK_INFO", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_get_network_info", + "description": "$string:ohos_desc_get_network_info" + }, + { + "name": "ohos.permission.PLACE_CALL", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": true, + "label": "$string:ohos_lab_place_call", + "description": "$string:ohos_desc_place_call" + }, + { + "name": "ohos.permission.CAMERA", + "grantMode": "user_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_camera", + "description": "$string:ohos_desc_camera" + }, + { + "name": "ohos.permission.SET_NETWORK_INFO", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_set_network_info", + "description": "$string:ohos_desc_set_network_info" + }, + { + "name": "ohos.permission.REMOVE_CACHE_FILES", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.READ_MEDIA", + "grantMode": "user_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": true, + "label": "$string:ohos_lab_read_media", + "description": "$string:ohos_desc_read_media" + }, + { + "name": "ohos.permission.REBOOT", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.RUNNING_LOCK", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.WRITE_MEDIA", + "grantMode": "user_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": true, + "label": "$string:ohos_lab_write_media", + "description": "$string:ohos_desc_write_media" + }, + { + "name": "com.huawei.permission.DISTRIBUTED_VIRTUALDEVICE", + "grantMode": "user_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_distributed_virtualdevice", + "description": "$string:ohos_desc_distributed_virtualdevice" + }, + { + "name": "ohos.permission.ENROLL_BIOMETRIC", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": false, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_enroll_biometric", + "description": "$string:ohos_desc_enroll_biometric" + }, + { + "name": "ohos.permission.ACCESS_BIOMETRIC", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": false, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_access_biometric", + "description": "$string:ohos_desc_access_biometric" + }, + { + "name": "ohos.permission.ACCESS_BIOMETRIC_INTERNAL", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": false, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_access_biometric_internal", + "description": "$string:ohos_desc_access_biometric_internal" + }, + { + "name": "ohos.permission.RESET_BIOMETRIC_LOCKOUT", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": false, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_reset_biometric_lockout", + "description": "$string:ohos_desc_reset_biometric_lockout" + }, + { + "name": "ohos.permission.SET_TIME", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_set_time", + "description": "$string:ohos_desc_set_time" + }, + { + "name": "ohos.permission.SET_TIME_ZONE", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_set_time_zone", + "description": "$string:ohos_desc_set_time_zone" + }, + { + "name": "ohos.permission.DOWNLOAD_SESSION_MANAGER", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_download_session_manager", + "description": "$string:ohos_desc_download_session_manager" + }, + { + "name": "ohos.permission.COMMONEVENT_STICKY", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": true, + "label": "$string:ohos_lab_commonevent_sticky", + "description": "$string:ohos_desc_commonevent_sticky" + }, + { + "name": "ohos.permission.SYSTEM_FLOAT_WINDOW", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.POWER_MANAGER", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.REFRESH_USER_ACTION", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.POWER_OPTIMIZATION", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.REBOOT_RECOVERY", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.MANAGE_LOCAL_ACCOUNTS", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_manage_local_accounts", + "description": "$string:ohos_desc_manage_local_accounts" + }, + { + "name": "ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_interact_across_local_accounts", + "description": "$string:ohos_desc_interact_across_local_accounts" + }, + { + "name": "ohos.permission.VIBRATE", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_vibrate", + "description": "$string:ohos_desc_vibrate" + }, + { + "name": "ohos.permission.ACTIVITY_MOTION", + "grantMode": "user_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_activity_motion", + "description": "$string:ohos_desc_activity_motion" + }, + { + "name": "ohos.permission.READ_HEALTH_DATA", + "grantMode": "user_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_read_health_data", + "description": "$string:ohos_desc_read_health_data" + }, + { + "name": "ohos.permission.CONNECT_IME_ABILITY", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_connect_ime_ability", + "description": "$string:ohos_desc_connect_ime_ability" + }, + { + "name": "ohos.permission.CONNECT_SCREEN_SAVER_ABILITY", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.READ_SCREEN_SAVER", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.WRITE_SCREEN_SAVER", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.SET_WALLPAPER", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_set_wallpaper", + "description": "$string:ohos_desc_set_wallpaper" + }, + { + "name": "ohos.permission.GET_WALLPAPER", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_get_wallpaper", + "description": "$string:ohos_desc_get_wallpaper" + }, + { + "name": "ohos.permission.CHANGE_ABILITY_ENABLED_STATE", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.ACCESS_MISSIONS", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.CLEAN_BACKGROUND_PROCESSES", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.UPDATE_CONFIGURATION", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.REVOKE_SENSITIVE_PERMISSIONS", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.GET_SENSITIVE_PERMISSIONS", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_interact_across_local_accounts_extension", + "description": "$string:ohos_desc_interact_across_local_accounts_extension" + }, + { + "name": "ohos.permission.LISTEN_BUNDLE_CHANGE", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.GET_BUNDLE_INFO", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.ACCELEROMETER", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_accelerometer", + "description": "$string:ohos_desc_accelerometer" + }, + { + "name": "ohos.permission.GYROSCOPE", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_gyroscope", + "description": "$string:ohos_desc_gyroscope" + }, + { + "name": "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.INSTALL_BUNDLE", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.MANAGE_SHORTCUTS", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.radio.ACCESS_FM_AM", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.SET_TELEPHONY_STATE", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_set_telephony_state", + "description": "$string:ohos_desc_set_telephony_state" + }, + { + "name": "ohos.permission.START_ABILIIES_FROM_BACKGROUND", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.BUNDLE_ACTIVE_INFO", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_bundle_active_info", + "description": "$string:ohos_desc_bundle_active_info" + }, + { + "name": "ohos.permission.START_INVISIBLE_ABILITY", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.sec.ACCESS_UDID", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.LAUNCH_DATA_PRIVACY_CENTER", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.MANAGE_MEDIA_RESOURCES", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.PUBLISH_AGENT_REMINDER", + "grantMode": "system_grant", + "availableScope": "normal", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_publish_agent_reminder", + "description": "$string:ohos_desc_publish_agent_reminder" + }, + { + "name": "ohos.permission.CONTROL_TASK_SYNC_ANIMATOR", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_control_task_sync_animator", + "description": "$string:ohos_desc_control_task_sync_animator" + }, + { + "name": "ohos.permission.INPUT_MONITORING", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.MANAGE_MISSIONS", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false + }, + { + "name": "ohos.permission.NOTIFICATION_CONTROLLER", + "grantMode": "system_grant", + "availableScope": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false, + "label": "$string:ohos_lab_notification_controller", + "description": "$string:ohos_desc_notification_controller" + }, + { + "name": "ohos.permission.CONNECTIVITY_INTERNAL", + "grantMode": "system_grant", + "availableScope": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + } + ] + } +} diff --git a/config/zh_CN/string.json b/config/zh_CN/string.json new file mode 100644 index 0000000000000000000000000000000000000000..5f0134df360bf6edb2a6679a88ee04959019d6cb --- /dev/null +++ b/config/zh_CN/string.json @@ -0,0 +1,428 @@ +{ + "string": [ + { + "name": "ohos_lab_answer_call", + "value": "绰" + }, + { + "name": "ohos_desc_answer_call", + "value": "Ӧý绰" + }, + { + "name": "ohos_lab_internet", + "value": "" + }, + { + "name": "ohos_desc_internet", + "value": "Ӧ÷硣" + }, + { + "name": "ohos_lab_modify_audio_settings", + "value": "Ƶ" + }, + { + "name": "ohos_desc_modify_audio_settings", + "value": "Ӧô򿪻رղͨ·" + }, + { + "name": "ohos_lab_read_calendar", + "value": "ȡ" + }, + { + "name": "ohos_desc_read_calendar", + "value": "Ӧöȡ" + }, + { + "name": "ohos_lab_read_call_log", + "value": "ȡͨ¼" + }, + { + "name": "ohos_desc_read_call_log", + "value": "Ӧöȡ豸ϵͨ¼Ϣ" + }, + { + "name": "ohos_lab_read_cell_messages", + "value": "ȡС㲥" + }, + { + "name": "ohos_desc_read_cell_messages", + "value": "Ӧöȡ豸յС㲥Ϣ" + }, + { + "name": "ohos_lab_read_contacts", + "value": "ȡͨѶ¼" + }, + { + "name": "ohos_desc_read_contacts", + "value": "Ӧöȡ豸ϴ洢ϵϢ" + }, + { + "name": "ohos_lab_get_telephony_state", + "value": "ȡ绰Ϣ" + }, + { + "name": "ohos_desc_get_telephony_state", + "value": "Ӧ÷豸ı롢豸ID䡢IMEIICCIDϢ" + }, + { + "name": "ohos_lab_read_messages", + "value": "ȡ̲" + }, + { + "name": "ohos_desc_read_messages", + "value": "Ӧöȡ豸յĶ̲Ϣ" + }, + { + "name": "ohos_lab_receive_mms", + "value": "ղ" + }, + { + "name": "ohos_desc_receive_mms", + "value": "Ӧýղš" + }, + { + "name": "ohos_lab_receive_sms", + "value": "ն" + }, + { + "name": "ohos_desc_receive_sms", + "value": "Ӧýնš" + }, + { + "name": "ohos_lab_receive_wap_messages", + "value": "WAPϢ" + }, + { + "name": "ohos_desc_receive_wap_messages", + "value": "ӦýWAPϢ" + }, + { + "name": "ohos_lab_microphone", + "value": "¼Ƶ" + }, + { + "name": "ohos_desc_microphone", + "value": "Ӧô򿪻ر¼ͨ·" + }, + { + "name": "ohos_lab_send_messages", + "value": "Ͷ̲" + }, + { + "name": "ohos_desc_send_messages", + "value": "Ӧ÷Ͷ̲š" + }, + { + "name": "ohos_lab_write_calendar", + "value": "½/޸/ɾ" + }, + { + "name": "ohos_desc_write_calendar", + "value": "Ӧ½/޸/ɾ" + }, + { + "name": "ohos_lab_write_call_log", + "value": "½/޸/ɾͨ¼" + }, + { + "name": "ohos_desc_write_call_log", + "value": "Ӧ½/޸/ɾ豸ϵͨ¼Ϣ" + }, + { + "name": "ohos_lab_write_contacts", + "value": "½/޸/ɾͨѶ¼" + }, + { + "name": "ohos_desc_write_contacts", + "value": "Ӧ½/޸/ɾ豸ϴ洢ϵϢ" + }, + { + "name": "ohos_lab_distributed_datasync", + "value": "ͬ豸ݽ" + }, + { + "name": "ohos_desc_distributed_datasync", + "value": "ӦԶ豸ûݣͼƬ֡ƵӦݵȣ" + }, + { + "name": "ohos_lab_manage_voicemail", + "value": "" + }, + { + "name": "ohos_desc_manage_voicemail", + "value": "Ӧù䡣" + }, + { + "name": "ohos_lab_location_in_background", + "value": "λȨ" + }, + { + "name": "ohos_desc_location_in_background", + "value": "Ӧں̨ʱȡλϢ" + }, + { + "name": "ohos_lab_location", + "value": "λȨ" + }, + { + "name": "ohos_desc_location", + "value": "Ӧǰ̨ʱȡλϢ" + }, + { + "name": "ohos_lab_media_location", + "value": "Ӧ÷λ" + }, + { + "name": "ohos_desc_media_location", + "value": "Ӧ÷ûýļеλϢ羭γϢҪȨޡ" + }, + { + "name": "ohos_lab_get_network_info", + "value": "ȡϢ" + }, + { + "name": "ohos_desc_get_network_info", + "value": "ӦûȡϢ" + }, + { + "name": "ohos_lab_place_call", + "value": "绰" + }, + { + "name": "ohos_desc_place_call", + "value": "ӦֱӲ绰" + }, + { + "name": "ohos_lab_camera", + "value": "Ƭ¼Ƶ" + }, + { + "name": "ohos_desc_camera", + "value": "ӦƬƵ" + }, + { + "name": "ohos_lab_set_network_info", + "value": "" + }, + { + "name": "ohos_desc_set_network_info", + "value": "Ӧ硣" + }, + { + "name": "ohos_lab_read_media", + "value": "Ӧöȡýļ" + }, + { + "name": "ohos_desc_read_media", + "value": "Ӧ÷ûýļƵƵͼƬȣҪȨޡ" + }, + { + "name": "ohos_lab_write_media", + "value": "Ӧöдýļ" + }, + { + "name": "ohos_desc_write_media", + "value": "ӦöдûýļƵƵͼƬȣҪȨޡ" + }, + { + "name": "ohos_lab_distributed_virtualdevice", + "value": "ֶ֧豸Эͬ豸" + }, + { + "name": "ohos_desc_distributed_virtualdevice", + "value": "Ӧ÷ֲ豸Աж豸Эͬ" + }, + { + "name": "ohos_lab_enroll_biometric", + "value": "" + }, + { + "name": "ohos_desc_enroll_biometric", + "value": "Ӧù" + }, + { + "name": "ohos_lab_access_biometric", + "value": "ʹ֤" + }, + { + "name": "ohos_desc_access_biometric", + "value": "Ӧʹ֤" + }, + { + "name": "ohos_lab_access_biometric_internal", + "value": "ϵͳӦʹ֤" + }, + { + "name": "ohos_desc_access_biometric_internal", + "value": "Ӧʹ֤" + }, + { + "name": "ohos_lab_reset_biometric_lockout", + "value": "֤ʧܼ" + }, + { + "name": "ohos_desc_reset_biometric_lockout", + "value": "Ӧ֤ʧܵļ" + }, + { + "name": "ohos_lab_set_time", + "value": "޸ϵͳʱ" + }, + { + "name": "ohos_desc_set_time", + "value": "Ӧ޸ϵͳʱ䡣" + }, + { + "name": "ohos_lab_set_time_zone", + "value": "޸ϵͳʱ" + }, + { + "name": "ohos_desc_set_time_zone", + "value": "Ӧ޸ϵͳʱ" + }, + { + "name": "ohos_lab_download_session_manager", + "value": "Ự" + }, + { + "name": "ohos_desc_download_session_manager", + "value": "ӦùỰ" + }, + { + "name": "ohos_lab_commonevent_sticky", + "value": "ճԹ¼" + }, + { + "name": "ohos_desc_commonevent_sticky", + "value": "Ӧ÷ճԹ¼" + }, + { + "name": "ohos_lab_manage_local_accounts", + "value": "˻" + }, + { + "name": "ohos_desc_manage_local_accounts", + "value": "ӦöԱ˻ɾIJ顣" + }, + { + "name": "ohos_lab_interact_across_local_accounts", + "value": "˻໥" + }, + { + "name": "ohos_desc_interact_across_local_accounts", + "value": "˺֮໥ʡ" + }, + { + "name": "ohos_lab_vibrate", + "value": "ʹ" + }, + { + "name": "ohos_desc_vibrate", + "value": "Ӧóʹ񶯡" + }, + { + "name": "ohos_lab_activity_motion", + "value": "ȡû˶״̬" + }, + { + "name": "ohos_desc_activity_motion", + "value": "Ӧóȡû˶״̬" + }, + { + "name": "ohos_lab_read_health_data", + "value": "ȡûĽ" + }, + { + "name": "ohos_desc_read_health_data", + "value": "ӦóȡûĽݡ" + }, + { + "name": "ohos_lab_connect_ime_ability", + "value": "뷨Ӧ" + }, + { + "name": "ohos_desc_connect_ime_ability", + "value": "뷨ܿôȨ޵档" + }, + { + "name": "ohos_lab_set_wallpaper", + "value": "þֽ̬" + }, + { + "name": "ohos_desc_set_wallpaper", + "value": "Ӧþֽ̬" + }, + { + "name": "ohos_lab_get_wallpaper", + "value": "ȡֽļ" + }, + { + "name": "ohos_desc_get_wallpaper", + "value": "Ӧöȡֽļ" + }, + { + "name": "ohos_lab_interact_across_local_accounts_extension", + "value": "˻չ" + }, + { + "name": "ohos_desc_interact_across_local_accounts_extension", + "value": "ӦÿźöӦõԽá" + }, + { + "name": "ohos_lab_accelerometer", + "value": "ȡٶȴ" + }, + { + "name": "ohos_desc_accelerometer", + "value": "Ӧóȡٶȴݡ" + }, + { + "name": "ohos_lab_gyroscope", + "value": "ȡǴ" + }, + { + "name": "ohos_desc_gyroscope", + "value": "ӦóȡǴݡ" + }, + { + "name": "ohos_lab_set_telephony_state", + "value": "õ绰Ϣ" + }, + { + "name": "ohos_desc_set_telephony_state", + "value": "Ӧ޸telephony״̬翪رշģʽ޸ģʽȡ" + }, + { + "name": "ohos_lab_bundle_active_info", + "value": "ѯӦǰ̨̨ʱ" + }, + { + "name": "ohos_desc_bundle_active_info", + "value": "ϵͳ/ȨӦòѯӦǰ̨̨ʱ䡣" + }, + { + "name": "ohos_lab_publish_agent_reminder", + "value": "" + }, + { + "name": "ohos_desc_publish_agent_reminder", + "value": "Ӧʹų́ѡ" + }, + { + "name": "ohos_lab_control_task_sync_animator", + "value": "ͬ" + }, + { + "name": "ohos_desc_control_task_sync_animator", + "value": "Ӧʹͬ" + }, + { + "name": "ohos_lab_notification_controller", + "value": "ϵͳӿ" + }, + { + "name": "ohos_desc_notification_controller", + "value": "Ӧʹ֪ͨӿڡ" + } + ] +} diff --git a/frameworks/accesstoken/BUILD.gn b/frameworks/accesstoken/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..b11ba2978b77b8614641ec42e3bad5ef30db3581 --- /dev/null +++ b/frameworks/accesstoken/BUILD.gn @@ -0,0 +1,52 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +################################################################ +# C++, Main source file here. +################################################################ +config("accesstoken_communication_adapter_cxx_public_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "//base/security/access_token/interfaces/innerkits/accesstoken/main/cpp/include", + ] +} + +ohos_shared_library("accesstoken_communication_adapter_cxx") { + subsystem_name = "security" + part_name = "access_token" + + public_configs = + [ ":accesstoken_communication_adapter_cxx_public_config" ] + + include_dirs = [ + "include", + "//base/security/access_token/interfaces/innerkits/accesstoken/main/cpp/include", + "//utils/native/base/include", + ] + + sources = [ + "src/permission_def_parcel.cpp", + "src/permission_state_full_parcel.cpp", + "src/hap_policy_parcel.cpp", + "src/hap_token_info_parcel.cpp", + "src/hap_info_parcel.cpp", + "src/native_token_info_parcel.cpp" + ] + + deps = [ "//utils/native/base:utils" ] + + external_deps = [ "ipc:ipc_core" ] +} diff --git a/frameworks/accesstoken/include/hap_info_parcel.h b/frameworks/accesstoken/include/hap_info_parcel.h new file mode 100644 index 0000000000000000000000000000000000000000..8f496175e23d78cc314654838ab443d6dc91fa3c --- /dev/null +++ b/frameworks/accesstoken/include/hap_info_parcel.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HAP_INFO_PARCEL_H +#define HAP_INFO_PARCEL_H + +#include "hap_token_info.h" + +#include "parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct HapInfoParcel final : public Parcelable { + HapInfoParcel() = default; + + ~HapInfoParcel() override = default; + + bool Marshalling(Parcel &out) const override; + + static HapInfoParcel *Unmarshalling(Parcel &in); + + HapInfoParams hapInfoParameter; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // HAP_INFO_PARCEL_H diff --git a/frameworks/accesstoken/include/hap_policy_parcel.h b/frameworks/accesstoken/include/hap_policy_parcel.h new file mode 100644 index 0000000000000000000000000000000000000000..7886bfbeb7fff89c01ecba7eb4a6a7f712221129 --- /dev/null +++ b/frameworks/accesstoken/include/hap_policy_parcel.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HAP_POLICY_PARCEL_H +#define HAP_POLICY_PARCEL_H + +#include "hap_token_info.h" +#include "permission_def_parcel.h" +#include "permission_state_full_parcel.h" + + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct HapPolicyParcel final : public Parcelable { + HapPolicyParcel() = default; + + ~HapPolicyParcel() override = default; + + bool Marshalling(Parcel &out) const override; + + static HapPolicyParcel *Unmarshalling(Parcel &in); + + HapPolicyParams hapPolicyParameter; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // HAP_POLICY_PARCEL_H diff --git a/frameworks/accesstoken/include/hap_token_info_parcel.h b/frameworks/accesstoken/include/hap_token_info_parcel.h new file mode 100644 index 0000000000000000000000000000000000000000..d13fda88a2ec7c89c5ab9be86f46f19db3d8841b --- /dev/null +++ b/frameworks/accesstoken/include/hap_token_info_parcel.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HAP_TOKEN_INFO_PARCEL_H +#define HAP_TOKEN_INFO_PARCEL_H + +#include "hap_token_info.h" + +#include "parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct HapTokenInfoParcel final : public Parcelable { + HapTokenInfoParcel() = default; + + ~HapTokenInfoParcel() override = default; + + bool Marshalling(Parcel &out) const override; + + static HapTokenInfoParcel *Unmarshalling(Parcel &in); + + HapTokenInfo hapTokenInfoParams; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // HAP_TOKEN_INFO_PARCEL_H diff --git a/frameworks/accesstoken/include/i_accesstoken_manager.h b/frameworks/accesstoken/include/i_accesstoken_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..aec6c78be4074d4045e73120b84fe278dc6df86a --- /dev/null +++ b/frameworks/accesstoken/include/i_accesstoken_manager.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef I_ACCESSTOKEN_MANAGER_H +#define I_ACCESSTOKEN_MANAGER_H + +#include + +#include "iremote_broker.h" +#include "errors.h" + +#include "access_token.h" +#include "permission_def_parcel.h" +#include "permission_state_full_parcel.h" +#include "hap_policy_parcel.h" +#include "hap_token_info_parcel.h" +#include "hap_info_parcel.h" +#include "native_token_info_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class IAccessTokenManager : public IRemoteBroker { +public: + static const int SA_ID_ACCESSTOKEN_MANAGER_SERVICE = 3503; + + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.security.accesstoken.IAccessTokenManager"); + + virtual int VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) = 0; + virtual int GetDefPermission(const std::string& permissionName, PermissionDefParcel& permissionDefResult) = 0; + virtual int GetDefPermissions(AccessTokenID tokenID, std::vector& permList) = 0; + virtual int GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) = 0; + virtual int GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) = 0; + virtual int GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) = 0; + virtual int RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) = 0; + virtual int ClearUserGrantedPermissionState(AccessTokenID tokenID) = 0; + virtual AccessTokenIDEx AllocHapToken(const HapInfoParcel& hapInfo, const HapPolicyParcel& policyParcel) = 0; + virtual int DeleteToken(AccessTokenID tokenID) = 0; + virtual int GetTokenType(AccessTokenID tokenID) = 0; + virtual int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) = 0; + virtual AccessTokenID GetHapTokenID(int userID, const std::string& bundleName, int instIndex) = 0; + virtual AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID) = 0; + virtual int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfoParcel& nativeTokenInfoRes) = 0; + virtual int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfoParcel& hapTokenInfoRes) = 0; + virtual int UpdateHapToken( + AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParcel& policyParcel) = 0; + + enum class InterfaceCode { + VERIFY_ACCESSTOKEN = 0xff10, + GET_DEF_PERMISSION = 0xff11, + GET_DEF_PERMISSIONS = 0xff12, + GET_REQ_PERMISSIONS = 0xff13, + GET_PERMISSION_FLAG = 0xff14, + GRANT_PERMISSION = 0xff15, + REVOKE_PERMISSION = 0xff16, + CLEAR_USER_GRANT_PERMISSION = 0xff17, + ALLOC_TOKEN_HAP = 0xff18, + TOKEN_DELETE = 0xff19, + GET_TOKEN_TYPE = 0xff20, + CHECK_NATIVE_DCAP = 0xff21, + GET_HAP_TOKEN_ID = 0xff22, + ALLOC_LOCAL_TOKEN_ID = 0xff23, + GET_NATIVE_TOKENINFO = 0xff24, + GET_HAP_TOKENINFO = 0xff25, + UPDATE_HAP_TOKEN = 0xff26, + }; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // I_ACCESSTOKEN_MANAGER_H diff --git a/frameworks/accesstoken/include/native_token_info_parcel.h b/frameworks/accesstoken/include/native_token_info_parcel.h new file mode 100644 index 0000000000000000000000000000000000000000..80bf8909cba6cc20826ab2b4276572fc058f91dc --- /dev/null +++ b/frameworks/accesstoken/include/native_token_info_parcel.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_TOKEN_INFO_PARCEL_H +#define NATIVE_TOKEN_INFO_PARCEL_H + +#include "native_token_info.h" + +#include "parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct NativeTokenInfoParcel final : public Parcelable { + NativeTokenInfoParcel() = default; + + ~NativeTokenInfoParcel() override = default; + + bool Marshalling(Parcel &out) const override; + + static NativeTokenInfoParcel *Unmarshalling(Parcel &in); + + NativeTokenInfo nativeTokenInfoParams; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // NATIVE_TOKEN_INFO_PARCEL_H diff --git a/frameworks/accesstoken/include/permission_def_parcel.h b/frameworks/accesstoken/include/permission_def_parcel.h new file mode 100644 index 0000000000000000000000000000000000000000..52e0a80c4197ea155f98ba126a7c13df22ac02f1 --- /dev/null +++ b/frameworks/accesstoken/include/permission_def_parcel.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_DEF_PARCEL_H +#define PERMISSION_DEF_PARCEL_H + +#include "permission_def.h" +#include "parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PermissionDefParcel final : public Parcelable { + PermissionDefParcel() = default; + + ~PermissionDefParcel() override = default; + + bool Marshalling(Parcel &out) const override; + + static PermissionDefParcel *Unmarshalling(Parcel &in); + + PermissionDef permissionDef; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_DEF_PARCEL_H diff --git a/frameworks/accesstoken/include/permission_state_full_parcel.h b/frameworks/accesstoken/include/permission_state_full_parcel.h new file mode 100644 index 0000000000000000000000000000000000000000..f4b8714a7a832d6291adff4992eee953e60f8994 --- /dev/null +++ b/frameworks/accesstoken/include/permission_state_full_parcel.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_PERMISSION_PERMISSION_STATE_FULL_PARCEL_H +#define INTERFACES_INNER_KITS_PERMISSION_PERMISSION_STATE_FULL_PARCEL_H + +#include "permission_state_full.h" +#include "parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PermissionStateFullParcel final : public Parcelable { + PermissionStateFullParcel() = default; + + ~PermissionStateFullParcel() override = default; + + bool Marshalling(Parcel &out) const override; + + static PermissionStateFullParcel *Unmarshalling(Parcel &in); + + PermissionStateFull permStatFull; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // INTERFACES_INNER_KITS_PERMISSION_PERMISSION_STATE_FULL_PARCEL_H diff --git a/frameworks/accesstoken/src/hap_info_parcel.cpp b/frameworks/accesstoken/src/hap_info_parcel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c0e3d984a4e0764e108080ab227cf5a97b3088c9 --- /dev/null +++ b/frameworks/accesstoken/src/hap_info_parcel.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hap_info_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +#define RETURN_IF_FALSE(expr) \ + if (!(expr)) { \ + return false; \ + } + +#define RELEASE_IF_FALSE(expr, obj) \ + if (!(expr)) { \ + delete (obj); \ + (obj) = nullptr; \ + return (obj); \ + } + +bool HapInfoParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteInt32(this->hapInfoParameter.userID)); + RETURN_IF_FALSE(out.WriteString(this->hapInfoParameter.bundleName)); + RETURN_IF_FALSE(out.WriteInt32(this->hapInfoParameter.instIndex)); + RETURN_IF_FALSE(out.WriteString(this->hapInfoParameter.appIDDesc)); + return true; +} + +HapInfoParcel* HapInfoParcel::Unmarshalling(Parcel& in) +{ + auto* hapInfoParcel = new (std::nothrow) HapInfoParcel(); + RELEASE_IF_FALSE(hapInfoParcel != nullptr, hapInfoParcel); + RELEASE_IF_FALSE(in.ReadInt32(hapInfoParcel->hapInfoParameter.userID), hapInfoParcel); + hapInfoParcel->hapInfoParameter.bundleName = in.ReadString(); + RELEASE_IF_FALSE(in.ReadInt32(hapInfoParcel->hapInfoParameter.instIndex), hapInfoParcel); + hapInfoParcel->hapInfoParameter.appIDDesc = in.ReadString(); + + return hapInfoParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/frameworks/accesstoken/src/hap_policy_parcel.cpp b/frameworks/accesstoken/src/hap_policy_parcel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0c14d15a3f7e6071cec75b31892685113ea889cd --- /dev/null +++ b/frameworks/accesstoken/src/hap_policy_parcel.cpp @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hap_policy_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +#define RETURN_IF_FALSE(expr) \ + if (!(expr)) { \ + return false; \ + } + +#define RELEASE_IF_FALSE(expr, obj) \ + if (!(expr)) { \ + delete (obj); \ + (obj) = nullptr; \ + return (obj); \ + } + +bool HapPolicyParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteInt32(this->hapPolicyParameter.apl)); + RETURN_IF_FALSE(out.WriteString(this->hapPolicyParameter.domain)); + + const std::vector& permList = this->hapPolicyParameter.permList; + int permListSize = permList.size(); + RETURN_IF_FALSE(out.WriteInt32(permListSize)); + + for (int i = 0; i < permListSize; i++) { + PermissionDefParcel permDefParcel; + permDefParcel.permissionDef = permList[i]; + out.WriteParcelable(&permDefParcel); + } + + const std::vector& permStateList = this->hapPolicyParameter.permStateList; + int permStateListSize = permStateList.size(); + RETURN_IF_FALSE(out.WriteInt32(permStateListSize)); + + for (int i = 0; i < permStateListSize; i++) { + PermissionStateFullParcel permStateParcel; + permStateParcel.permStatFull = permStateList[i]; + out.WriteParcelable(&permStateParcel); + } + + return true; +} + +HapPolicyParcel* HapPolicyParcel::Unmarshalling(Parcel& in) +{ + auto* hapPolicyParcel = new (std::nothrow) HapPolicyParcel(); + RELEASE_IF_FALSE(hapPolicyParcel != nullptr, hapPolicyParcel); + + int32_t apl; + RELEASE_IF_FALSE(in.ReadInt32(apl), hapPolicyParcel); + hapPolicyParcel->hapPolicyParameter.apl = ATokenAplEnum(apl); + + hapPolicyParcel->hapPolicyParameter.domain = in.ReadString(); + + int permListSize; + RELEASE_IF_FALSE(in.ReadInt32(permListSize), hapPolicyParcel); + + for (int i = 0; i < permListSize; i++) { + sptr permDefParcel = in.ReadParcelable(); + RELEASE_IF_FALSE(permDefParcel != nullptr, hapPolicyParcel); + hapPolicyParcel->hapPolicyParameter.permList.emplace_back(permDefParcel->permissionDef); + } + + int permStateListSize; + RELEASE_IF_FALSE(in.ReadInt32(permStateListSize), hapPolicyParcel); + for (int i = 0; i < permStateListSize; i++) { + sptr permissionStateParcel = in.ReadParcelable(); + RELEASE_IF_FALSE(permissionStateParcel != nullptr, hapPolicyParcel); + hapPolicyParcel->hapPolicyParameter.permStateList.emplace_back(permissionStateParcel->permStatFull); + } + return hapPolicyParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/accesstoken/src/hap_token_info_parcel.cpp b/frameworks/accesstoken/src/hap_token_info_parcel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5d5c2c519b97f1a957a1b0cde687d36f9a6e6f43 --- /dev/null +++ b/frameworks/accesstoken/src/hap_token_info_parcel.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hap_token_info_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +#define RETURN_IF_FALSE(expr) \ + if (!(expr)) { \ + return false; \ + } + +#define RELEASE_IF_FALSE(expr, obj) \ + if (!(expr)) { \ + delete (obj); \ + (obj) = nullptr; \ + return (obj); \ + } + +bool HapTokenInfoParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteInt32(this->hapTokenInfoParams.apl)); + RETURN_IF_FALSE(out.WriteUint8(this->hapTokenInfoParams.ver)); + RETURN_IF_FALSE(out.WriteInt32(this->hapTokenInfoParams.userID)); + RETURN_IF_FALSE(out.WriteString(this->hapTokenInfoParams.bundleName)); + RETURN_IF_FALSE(out.WriteInt32(this->hapTokenInfoParams.instIndex)); + RETURN_IF_FALSE(out.WriteString(this->hapTokenInfoParams.appID)); + RETURN_IF_FALSE(out.WriteString(this->hapTokenInfoParams.deviceID)); + RETURN_IF_FALSE(out.WriteUint32(this->hapTokenInfoParams.tokenID)); + RETURN_IF_FALSE(out.WriteUint32(this->hapTokenInfoParams.tokenAttr)); + return true; +} + +HapTokenInfoParcel* HapTokenInfoParcel::Unmarshalling(Parcel& in) +{ + auto* hapTokenInfoParcel = new (std::nothrow) HapTokenInfoParcel(); + RELEASE_IF_FALSE(hapTokenInfoParcel != nullptr, hapTokenInfoParcel); + int apl; + int8_t ver; + RELEASE_IF_FALSE(in.ReadInt32(apl), hapTokenInfoParcel); + hapTokenInfoParcel->hapTokenInfoParams.apl = ATokenAplEnum(apl); + RELEASE_IF_FALSE(in.ReadInt8(ver), hapTokenInfoParcel); + hapTokenInfoParcel->hapTokenInfoParams.ver = ver; + RELEASE_IF_FALSE(in.ReadInt32(hapTokenInfoParcel->hapTokenInfoParams.userID), hapTokenInfoParcel); + hapTokenInfoParcel->hapTokenInfoParams.bundleName = in.ReadString(); + RELEASE_IF_FALSE(in.ReadInt32(hapTokenInfoParcel->hapTokenInfoParams.instIndex), hapTokenInfoParcel); + hapTokenInfoParcel->hapTokenInfoParams.appID = in.ReadString(); + hapTokenInfoParcel->hapTokenInfoParams.deviceID = in.ReadString(); + RELEASE_IF_FALSE(in.ReadUint32(hapTokenInfoParcel->hapTokenInfoParams.tokenID), hapTokenInfoParcel); + RELEASE_IF_FALSE(in.ReadUint32(hapTokenInfoParcel->hapTokenInfoParams.tokenAttr), hapTokenInfoParcel); + return hapTokenInfoParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/accesstoken/src/native_token_info_parcel.cpp b/frameworks/accesstoken/src/native_token_info_parcel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f623cfd0b5b03779800e14af87cb544952c2bdc6 --- /dev/null +++ b/frameworks/accesstoken/src/native_token_info_parcel.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_token_info_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +#define RETURN_IF_FALSE(expr) \ + if (!(expr)) { \ + return false; \ + } + +#define RELEASE_IF_FALSE(expr, obj) \ + if (!(expr)) { \ + delete (obj); \ + (obj) = nullptr; \ + return (obj); \ + } + +bool NativeTokenInfoParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteInt32(this->nativeTokenInfoParams.apl)); + RETURN_IF_FALSE(out.WriteUint8(this->nativeTokenInfoParams.ver)); + RETURN_IF_FALSE(out.WriteString(this->nativeTokenInfoParams.processName)); + RETURN_IF_FALSE(out.WriteUint32(this->nativeTokenInfoParams.tokenID)); + RETURN_IF_FALSE(out.WriteUint32(this->nativeTokenInfoParams.tokenAttr)); + + int dcapSize = (this->nativeTokenInfoParams.dcap).size(); + RETURN_IF_FALSE(out.WriteInt32(dcapSize)); + + for (int i = 0; i < dcapSize; i++) { + RETURN_IF_FALSE(out.WriteString(this->nativeTokenInfoParams.dcap[i])); + } + + return true; +} + +NativeTokenInfoParcel* NativeTokenInfoParcel::Unmarshalling(Parcel& in) +{ + auto* nativeTokenInfoParcel = new (std::nothrow) NativeTokenInfoParcel(); + RELEASE_IF_FALSE(nativeTokenInfoParcel != nullptr, nativeTokenInfoParcel); + + int32_t apl; + int8_t ver; + RELEASE_IF_FALSE(in.ReadInt32(apl), nativeTokenInfoParcel); + RELEASE_IF_FALSE(in.ReadInt8(ver), nativeTokenInfoParcel); + nativeTokenInfoParcel->nativeTokenInfoParams.apl = ATokenAplEnum(apl); + nativeTokenInfoParcel->nativeTokenInfoParams.ver = ver; + + nativeTokenInfoParcel->nativeTokenInfoParams.processName = in.ReadString(); + RELEASE_IF_FALSE(in.ReadUint32(nativeTokenInfoParcel->nativeTokenInfoParams.tokenID), nativeTokenInfoParcel); + RELEASE_IF_FALSE(in.ReadUint32(nativeTokenInfoParcel->nativeTokenInfoParams.tokenAttr), nativeTokenInfoParcel); + + int dcapSize; + RELEASE_IF_FALSE(in.ReadInt32(dcapSize), nativeTokenInfoParcel); + + for (int i = 0; i < dcapSize; i++) { + nativeTokenInfoParcel->nativeTokenInfoParams.dcap[i] = in.ReadString(); + } + return nativeTokenInfoParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/accesstoken/src/permission_def_parcel.cpp b/frameworks/accesstoken/src/permission_def_parcel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..421731e9fc248aa3949a168432b48bfdd0b645c2 --- /dev/null +++ b/frameworks/accesstoken/src/permission_def_parcel.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_def_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +#define RETURN_IF_FALSE(expr) \ + if (!(expr)) { \ + return false; \ + } + +#define RELEASE_IF_FALSE(expr, obj) \ + if (!(expr)) { \ + delete (obj); \ + (obj) = nullptr; \ + return (obj); \ + } + +bool PermissionDefParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteString(this->permissionDef.permissionName)); + RETURN_IF_FALSE(out.WriteString(this->permissionDef.bundleName)); + RETURN_IF_FALSE(out.WriteInt32(this->permissionDef.grantMode)); + RETURN_IF_FALSE(out.WriteInt32(this->permissionDef.availableScope)); + RETURN_IF_FALSE(out.WriteString(this->permissionDef.label)); + RETURN_IF_FALSE(out.WriteInt32(this->permissionDef.labelId)); + RETURN_IF_FALSE(out.WriteString(this->permissionDef.description)); + RETURN_IF_FALSE(out.WriteInt32(this->permissionDef.descriptionId)); + return true; +} + +PermissionDefParcel* PermissionDefParcel::Unmarshalling(Parcel& in) +{ + auto* permissionDefParcel = new (std::nothrow) PermissionDefParcel(); + RELEASE_IF_FALSE(permissionDefParcel != nullptr, permissionDefParcel); + permissionDefParcel->permissionDef.permissionName = in.ReadString(); + permissionDefParcel->permissionDef.bundleName = in.ReadString(); + RELEASE_IF_FALSE(in.ReadInt32(permissionDefParcel->permissionDef.grantMode), permissionDefParcel); + RELEASE_IF_FALSE(in.ReadInt32(permissionDefParcel->permissionDef.availableScope), permissionDefParcel); + permissionDefParcel->permissionDef.label = in.ReadString(); + RELEASE_IF_FALSE(in.ReadInt32(permissionDefParcel->permissionDef.labelId), permissionDefParcel); + permissionDefParcel->permissionDef.description = in.ReadString(); + RELEASE_IF_FALSE(in.ReadInt32(permissionDefParcel->permissionDef.descriptionId), permissionDefParcel); + return permissionDefParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/accesstoken/src/permission_state_full_parcel.cpp b/frameworks/accesstoken/src/permission_state_full_parcel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..50ce4bf2b09293e45639d0dbc7082fac5359ad74 --- /dev/null +++ b/frameworks/accesstoken/src/permission_state_full_parcel.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_state_full_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +#define RETURN_IF_FALSE(expr) \ + if (!(expr)) { \ + return false; \ + } + +#define RELEASE_IF_FALSE(expr, obj) \ + if (!(expr)) { \ + delete (obj); \ + (obj) = nullptr; \ + return (obj); \ + } + +bool PermissionStateFullParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteString(this->permStatFull.permissionName)); + RETURN_IF_FALSE(out.WriteBool(this->permStatFull.isGeneral)); + + RETURN_IF_FALSE(out.WriteInt32(this->permStatFull.resDeviceID.size())); + for (auto devId : this->permStatFull.resDeviceID) { + RETURN_IF_FALSE(out.WriteString(devId)); + } + + RETURN_IF_FALSE(out.WriteInt32(this->permStatFull.grantStatus.size())); + for (auto grantStat : this->permStatFull.grantStatus) { + RETURN_IF_FALSE(out.WriteInt32(grantStat)); + } + + RETURN_IF_FALSE(out.WriteInt32(this->permStatFull.grantFlags.size())); + for (auto grantFlag : this->permStatFull.grantFlags) { + RETURN_IF_FALSE(out.WriteInt32(grantFlag)); + } + return true; +} + +PermissionStateFullParcel* PermissionStateFullParcel::Unmarshalling(Parcel& in) +{ + auto* permissionStateParcel = new (std::nothrow) PermissionStateFullParcel(); + RELEASE_IF_FALSE(permissionStateParcel != nullptr, permissionStateParcel); + + RELEASE_IF_FALSE(in.ReadString(permissionStateParcel->permStatFull.permissionName), permissionStateParcel); + RELEASE_IF_FALSE(in.ReadBool(permissionStateParcel->permStatFull.isGeneral), permissionStateParcel); + + int resIdSize = 0; + RELEASE_IF_FALSE(in.ReadInt32(resIdSize), permissionStateParcel); + for (int i = 0; i < resIdSize; i++) { + std::string resId; + RELEASE_IF_FALSE(in.ReadString(resId), permissionStateParcel); + permissionStateParcel->permStatFull.resDeviceID.emplace_back(resId); + } + + int grantStatsSize = 0; + RELEASE_IF_FALSE(in.ReadInt32(grantStatsSize), permissionStateParcel); + for (int i = 0; i < grantStatsSize; i++) { + int grantStat; + RELEASE_IF_FALSE(in.ReadInt32(grantStat), permissionStateParcel); + permissionStateParcel->permStatFull.grantStatus.emplace_back(grantStat); + } + + int grantFlagSize = 0; + RELEASE_IF_FALSE(in.ReadInt32(grantFlagSize), permissionStateParcel); + for (int i = 0; i < grantFlagSize; i++) { + int flag; + RELEASE_IF_FALSE(in.ReadInt32(flag), permissionStateParcel); + permissionStateParcel->permStatFull.grantFlags.emplace_back(flag); + } + return permissionStateParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/common/BUILD.gn b/frameworks/common/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..b63c67b3c222d47a82255414167f29f5121f59f8 --- /dev/null +++ b/frameworks/common/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +################################################################ +# C++, Main source file here. +################################################################ +config("accesstoken_common_cxx_public_config") { + visibility = [ ":*" ] + include_dirs = [ "main/cpp/include" ] +} + +ohos_shared_library("accesstoken_common_cxx") { + subsystem_name = "security" + part_name = "access_token" + + public_configs = [ ":accesstoken_common_cxx_public_config" ] + + include_dirs = [ + "include", + "//utils/system/safwk/native/include", + "//third_party/mbedtls/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/main/cpp/include", + ] + + sources = [ + "src/data_validator.cpp", + "src/random_mbedtls.cpp" + ] + + deps = [ + "//utils/native/base:utils", + "//third_party/mbedtls:mbedtls_shared", + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] +} diff --git a/frameworks/common/include/accesstoken_log.h b/frameworks/common/include/accesstoken_log.h new file mode 100644 index 0000000000000000000000000000000000000000..3fb142587227c69a27538bb953da33d1b954b74a --- /dev/null +++ b/frameworks/common/include/accesstoken_log.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_LOG_H +#define ACCESSTOKEN_LOG_H + +#ifdef HILOG_ENABLE + +#include "hilog/log.h" + +#ifndef __cplusplus + +#define ACCESSTOKEN_LOG_DEBUG(fmt, ...) HILOG_DEBUG(LOG_CORE, fmt, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_INFO(fmt, ...) HILOG_INFO(LOG_CORE, fmt, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_WARN(fmt, ...) HILOG_WARN(LOG_CORE, fmt, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_ERROR(fmt, ...) HILOG_ERROR(LOG_CORE, fmt, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_FATAL(fmt, ...) HILOG_FATAL(LOG_CORE, fmt, ##__VA_ARGS__) + +#else + +#define ACCESSTOKEN_LOG_DEBUG(label, fmt, ...) OHOS::HiviewDFX::HiLog::Debug(label, fmt, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_INFO(label, fmt, ...) OHOS::HiviewDFX::HiLog::Info(label, fmt, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_WARN(label, fmt, ...) OHOS::HiviewDFX::HiLog::Warn(label, fmt, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_ERROR(label, fmt, ...) OHOS::HiviewDFX::HiLog::Error(label, fmt, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_FATAL(label, fmt, ...) OHOS::HiviewDFX::HiLog::Fatal(label, fmt, ##__VA_ARGS__) + +#endif // __cplusplus + +/* define LOG_TAG as "security_*" at your submodule, * means your submodule name such as "security_dac" */ +#undef LOG_TAG +#undef LOG_DOMAIN + +static constexpr unsigned int SECURITY_DOMAIN_ACCESSTOKEN = 0xD002F01; + +#else + +#include +#include + +/* define LOG_TAG as "security_*" at your submodule, * means your submodule name such as "security_dac" */ +#undef LOG_TAG + +#define ACCESSTOKEN_LOG_DEBUG(fmt, ...) printf("[%s] debug: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_INFO(fmt, ...) printf("[%s] info: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_WARN(fmt, ...) printf("[%s] warn: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_ERROR(fmt, ...) printf("[%s] error: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_FATAL(fmt, ...) printf("[%s] fatal: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) + +#endif // HILOG_ENABLE + +#endif // ACCESSTOKEN_LOG_H diff --git a/frameworks/common/include/data_validator.h b/frameworks/common/include/data_validator.h new file mode 100644 index 0000000000000000000000000000000000000000..dc486baa6bf0c7867926fe759d38a6e567a37d74 --- /dev/null +++ b/frameworks/common/include/data_validator.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#ifndef DATA_VALIDATOR_H +#define DATA_VALIDATOR_H +namespace OHOS { +namespace Security { +namespace AccessToken { +class DataValidator final { +public: + static bool IsBundleNameValid(const std::string& bundleName); + + static bool IsPermissionNameValid(const std::string& permissionName); + + static bool IsUserIdValid(const int userId); + + static bool IsAppIDDescValid(const std::string& appIDDesc); + + static bool IsDomainValid(const std::string& domain); + + static bool IsAplNumValid(const int apl); +private: + const static int MAX_LENGTH = 256; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // DATA_VALIDATOR_H diff --git a/frameworks/common/include/random.h b/frameworks/common/include/random.h new file mode 100644 index 0000000000000000000000000000000000000000..9362764210314841612be570b5edb67170e0b3ad --- /dev/null +++ b/frameworks/common/include/random.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_RANDOM_H +#define ACCESSTOKEN_RANDOM_H + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +unsigned int GetRandomUint32(); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ +#endif /* ACCESSTOKEN_RANDOM_H */ diff --git a/frameworks/common/include/random_mbedtls.h b/frameworks/common/include/random_mbedtls.h new file mode 100644 index 0000000000000000000000000000000000000000..ffd3ddd147ee2478af4cac6e74196d9c27f455ce --- /dev/null +++ b/frameworks/common/include/random_mbedtls.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESS_TOKEN_RANDOM_MBEDTLS +#define ACCESS_TOKEN_RANDOM_MBEDTLS + +#include "rwlock.h" +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/entropy.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class RandomMbedtls { +public: + static RandomMbedtls& GetInstance(); + int GenerateRandomArray(unsigned char *randStr, unsigned int len); + ~RandomMbedtls() {}; + static unsigned int GetRandomUint32(); + +private: + RandomMbedtls() : initFlag_(false) {}; + mbedtls_entropy_context entropy_; + mbedtls_ctr_drbg_context ctrDrbg_; + OHOS::Utils::RWLock randomLock_; + bool initFlag_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESS_TOKEN_RANDOM_MBEDTLS diff --git a/frameworks/common/src/data_validator.cpp b/frameworks/common/src/data_validator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8928c3d777aa95c540d53d04230e4e5a56ed8627 --- /dev/null +++ b/frameworks/common/src/data_validator.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "data_validator.h" +#include "access_token.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool DataValidator::IsBundleNameValid(const std::string& bundleName) +{ + return !bundleName.empty() && (bundleName.length() <= MAX_LENGTH); +} + +bool DataValidator::IsPermissionNameValid(const std::string& permissionName) +{ + return !permissionName.empty() && (permissionName.length() <= MAX_LENGTH); +} + +bool DataValidator::IsUserIdValid(const int userId) +{ + return userId >= 0; +} + +bool DataValidator::IsAppIDDescValid(const std::string& appIDDesc) +{ + return !appIDDesc.empty() && (appIDDesc.length() <= MAX_LENGTH); +} + +bool DataValidator::IsDomainValid(const std::string& domain) +{ + return !domain.empty() && (domain.length() <= MAX_LENGTH); +} + +bool DataValidator::IsAplNumValid(const int apl) +{ + return (apl == APL_NORMAL || apl == APL_SYSTEM_BASIC || apl == APL_SYSTEM_CORE); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/frameworks/common/src/random_mbedtls.cpp b/frameworks/common/src/random_mbedtls.cpp new file mode 100644 index 0000000000000000000000000000000000000000..20d7dfbbcaf6e4d50df90e605e5ccdbbb1fec644 --- /dev/null +++ b/frameworks/common/src/random_mbedtls.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "random_mbedtls.h" +#include "access_token.h" + +using OHOS::Security::AccessToken::RandomMbedtls; +using OHOS::Security::AccessToken::RET_SUCCESS; + +namespace OHOS { +namespace Security { +namespace AccessToken { +extern "C" unsigned int GetRandomUint32() +{ + unsigned int rand; + int ret = RandomMbedtls::GetInstance().GenerateRandomArray((unsigned char *)&rand, sizeof(rand)); + if (ret != RET_SUCCESS) { + return 0; + } + return rand; +} + +int RandomMbedtls::GenerateRandomArray(unsigned char *randStr, unsigned int len) +{ + if (randStr == NULL || len == 0) { + return RET_FAILED; + } + int ret; + + Utils::UniqueWriteGuard infoGuard(this->randomLock_); + if (initFlag_ == false) { + mbedtls_ctr_drbg_init(&ctrDrbg_); + mbedtls_entropy_init(&entropy_); + ret = mbedtls_ctr_drbg_seed(&ctrDrbg_, mbedtls_entropy_func, &entropy_, NULL, 0); + if (ret != 0) { + return RET_FAILED; + } + initFlag_ = true; + } + + ret = mbedtls_ctr_drbg_random(&ctrDrbg_, randStr, len); + if (ret != 0) { + return RET_FAILED; + } + return RET_SUCCESS; +} + +RandomMbedtls& RandomMbedtls::GetInstance() +{ + static RandomMbedtls instance; + return instance; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/frameworks/tokensync/include/i_tokensync_manager.h b/frameworks/tokensync/include/i_tokensync_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..9a2769ee3d8b13a291b23c949bfab9852ddaccea --- /dev/null +++ b/frameworks/tokensync/include/i_tokensync_manager.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef I_TOKENSYNC_MANAGER_H +#define I_TOKENSYNC_MANAGER_H + +#include + +#include "iremote_broker.h" +#include "errors.h" + +namespace OHOS { +namespace Security { +namespace TokenSync { +class ITokenSyncManager : public IRemoteBroker { +public: + static const int SA_ID_TOKENSYNC_MANAGER_SERVICE = 3504; + + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.security.accesstoken.ITokenSyncManager"); + + virtual int VerifyPermission(const std::string& bundleName, const std::string& permissionName, int userId) = 0; + + enum class InterfaceCode { + VERIFY_PERMISSION = 0xff01, + }; +}; +} // namespace TokenSync +} // namespace Security +} // namespace OHOS + +#endif // I_TOKENSYNC_MANAGER_H diff --git a/interfaces/innerkits/accesstoken/BUILD.gn b/interfaces/innerkits/accesstoken/BUILD.gn index 2cc576843c7f6a990473d776dec065d9a24188c8..b6cc8e22c48ca5c14439b842f0368825a622ab0b 100644 --- a/interfaces/innerkits/accesstoken/BUILD.gn +++ b/interfaces/innerkits/accesstoken/BUILD.gn @@ -16,7 +16,7 @@ import("//build/ohos.gni") ################################################################ # C++, Main, source file here. ################################################################ -config("accesstoken_sdk_cxx_public_config_standard") { +config("accesstoken") { visibility = [ ":*" ] include_dirs = [ "main/cpp/include" ] } @@ -27,14 +27,15 @@ ohos_shared_library("libaccesstoken_sdk") { output_name = "libaccesstoken_sdk" - public_configs = [ ":accesstoken_sdk_cxx_public_config_standard" ] + public_configs = [ ":accesstoken" ] include_dirs = [ "//utils/native/base/include", "main/cpp/include", "main/cpp/src", - "//base/security/access_token/frameworks/accesstoken", - "//base/security/access_token/nterfaces/innerkits/accesstoken/main/cpp/include", + "//base/security/access_token/frameworks/accesstoken/include", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/main/cpp/include" ] sources = [ @@ -44,8 +45,7 @@ ohos_shared_library("libaccesstoken_sdk") { ] deps = [ - "//base/security/permission/frameworks/permission_standard/permissioncommunicationadapter:permission_standard_communication_adapter_cxx", - "//base/security/permission/frameworks/permission_standard/permissioninfrastructure:permission_standard_infrastructure_cxx", + "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", "//utils/native/base:utils", ] diff --git a/interfaces/innerkits/accesstoken/main/cpp/include/access_token.h b/interfaces/innerkits/accesstoken/main/cpp/include/access_token.h new file mode 100644 index 0000000000000000000000000000000000000000..5f8909948b71c2c2027b79a8efb3b951c225d64a --- /dev/null +++ b/interfaces/innerkits/accesstoken/main/cpp/include/access_token.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESS_TOKEN_DEF_H +#define ACCESS_TOKEN_DEF_H + +namespace OHOS { +namespace Security { +namespace AccessToken { +typedef unsigned int AccessTokenID; +typedef unsigned int AccessTokenAttr; +static const int DEFAULT_TOKEN_VERSION = 1; + +enum AccessTokenKitRet { + RET_FAILED = -1, + RET_SUCCESS = 0, +}; + +typedef struct { + unsigned int tokenUniqueID : 24; + unsigned int res : 3; + unsigned int type : 2; + unsigned int version : 3; +} AccessTokenIDInner; + +typedef enum TypeATokenTypeEnum { + TOKEN_INVALID = -1, + TOKEN_HAP = 0, + TOKEN_NATIVE, +} ATokenTypeEnum; + +typedef enum TypeATokenAplEnum { + APL_NORMAL = 1, + APL_SYSTEM_BASIC = 2, + APL_SYSTEM_CORE = 3, +} ATokenAplEnum; + +typedef union { + unsigned long long tokenIDEx; + struct { + AccessTokenID tokenID; + AccessTokenAttr tokenAttr; + } tokenIdExStruct; +} AccessTokenIDEx; + +typedef enum TypePermissionState { + PERMISSION_DENIED = -1, + PERMISSION_GRANTED = 0, +} PermissionState; + +typedef enum TypeGrantMode { + USER_GRANT = 0, + SYSTEM_GRANT = 1, +} GrantMode; + +typedef enum TypeAvailableScope { + AVAILABLE_SCOPE_ALL = 1 << 0, + AVAILABLE_SCOPE_SIGNATURE = 1 << 1, + AVAILABLE_SCOPE_RESTRICTED = 1 << 2 +} AvailableScope; + +typedef enum TypePermissionFlag { + PERMISSION_USER_SET = 1 << 0, + PERMISSION_USER_FIXED = 1 << 1, + PERMISSION_SYSTEM_FIXED = 1 << 2, +} PermissionFlag; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESS_TOKEN_DEF_H diff --git a/interfaces/innerkits/accesstoken/main/cpp/include/accesstoken_kit.h b/interfaces/innerkits/accesstoken/main/cpp/include/accesstoken_kit.h index 22fedd97a90f46c80ed4b1c0e784c90b8464b5c1..c8ccb5860fb7a5907565d3a6c521b36b124c30eb 100644 --- a/interfaces/innerkits/accesstoken/main/cpp/include/accesstoken_kit.h +++ b/interfaces/innerkits/accesstoken/main/cpp/include/accesstoken_kit.h @@ -1,32 +1,57 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_INNER_KITS_ACCESSTOKEN_KIT_H -#define INTERFACES_INNER_KITS_ACCESSTOKEN_KIT_H - -#include -#include "accesstoken.h" - -namespace OHOS { -namespace Security { -namespace AccessToken { -class AccessTokenKit { -public: - static int VerifyAccesstoken(AccessTokenID tokenID, const std::string& permissionName); -}; -} // namespace AccessToken -} // namespace Security -} // namespace OHOS -#endif +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_ACCESSTOKEN_KIT_H +#define INTERFACES_INNER_KITS_ACCESSTOKEN_KIT_H + +#include +#include + +#include "access_token.h" +#include "hap_token_info.h" +#include "native_token_info.h" +#include "permission_def.h" +#include "permission_state_full.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class AccessTokenKit { +public: + static AccessTokenIDEx AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy); + static AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID); + static int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParams& policy); + static int DeleteToken(AccessTokenID tokenID); + static int GetTokenType(AccessTokenID tokenID); + static int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap); + static AccessTokenID GetHapTokenID(int userID, const std::string& bundleName, int instIndex); + static int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes); + static int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& nativeTokenInfoRes); + static int VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName); + static int VerifyAccessToken( + AccessTokenID callerTokenID, AccessTokenID firstTokenID, const std::string& permissionName); + static int GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult); + static int GetDefPermissions(AccessTokenID tokenID, std::vector& permList); + static int GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant); + static int GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName); + static int GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag); + static int RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag); + static int ClearUserGrantedPermissionState(AccessTokenID tokenID); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif diff --git a/interfaces/innerkits/accesstoken/main/cpp/include/hap_token_info.h b/interfaces/innerkits/accesstoken/main/cpp/include/hap_token_info.h new file mode 100644 index 0000000000000000000000000000000000000000..26477f893f39bc6c12d00651283a3af1629c0c06 --- /dev/null +++ b/interfaces/innerkits/accesstoken/main/cpp/include/hap_token_info.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_HAP_TOKEN_INFO_H +#define ACCESSTOKEN_HAP_TOKEN_INFO_H + +#include "access_token.h" +#include "permission_def.h" +#include "permission_state_full.h" +#include +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class HapInfoParams final { +public: + int userID; + std::string bundleName; + int instIndex; + std::string appIDDesc; +}; + +class HapPolicyParams final { +public: + ATokenAplEnum apl; + std::string domain; + std::vector permList; + std::vector permStateList; +}; + +class HapTokenInfo final { +public: + ATokenAplEnum apl; + char ver; + int userID; + std::string bundleName; + int instIndex; + std::string appID; + std::string deviceID; + AccessTokenID tokenID; + AccessTokenAttr tokenAttr; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_HAP_TOKEN_INFO_H diff --git a/interfaces/innerkits/accesstoken/main/cpp/include/native_token_info.h b/interfaces/innerkits/accesstoken/main/cpp/include/native_token_info.h new file mode 100644 index 0000000000000000000000000000000000000000..60b427f3598d5fc059a3f4fa10ab15d185a01f0c --- /dev/null +++ b/interfaces/innerkits/accesstoken/main/cpp/include/native_token_info.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_NATIVE_TOKEN_INFO_H +#define ACCESSTOKEN_NATIVE_TOKEN_INFO_H + +#include "access_token.h" +#include +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class NativeTokenInfo final { +public: + ATokenAplEnum apl; + unsigned char ver; + std::string processName; + std::vector dcap; + AccessTokenID tokenID; + AccessTokenAttr tokenAttr; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_NATIVE_TOKEN_INFO_H diff --git a/interfaces/innerkits/accesstoken/main/cpp/include/permission_def.h b/interfaces/innerkits/accesstoken/main/cpp/include/permission_def.h new file mode 100644 index 0000000000000000000000000000000000000000..a08b3103c26b05333aee4690f28e53cc9f16e18e --- /dev/null +++ b/interfaces/innerkits/accesstoken/main/cpp/include/permission_def.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_ACCESSTOKEN_PERMISSION_DEF_H +#define INTERFACES_INNER_KITS_ACCESSTOKEN_PERMISSION_DEF_H + +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionDef final { +public: + std::string permissionName; + std::string bundleName; + int grantMode; + int availableScope; + std::string label; + int labelId; + std::string description; + int descriptionId; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // INTERFACES_INNER_KITS_ACCESSTOKEN_PERMISSION_DEF_H diff --git a/interfaces/innerkits/accesstoken/main/cpp/include/permission_state_full.h b/interfaces/innerkits/accesstoken/main/cpp/include/permission_state_full.h new file mode 100644 index 0000000000000000000000000000000000000000..17b8b0137879fa2764368d2e7ce20c00d526fb75 --- /dev/null +++ b/interfaces/innerkits/accesstoken/main/cpp/include/permission_state_full.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_PERMISSION_PERMISSION_STATE_FULL_H +#define INTERFACES_INNER_KITS_PERMISSION_PERMISSION_STATE_FULL_H + +#include +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionStateFull final { +public: + std::string permissionName; + bool isGeneral; + std::vector resDeviceID; + std::vector grantStatus; + std::vector grantFlags; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // INTERFACES_INNER_KITS_PERMISSION_PERMISSION_STATE_FULL_H diff --git a/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_kit.cpp b/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_kit.cpp index 1e0e8e06e7bc66a3c83dd00cbc9a4a2b9a6409a5..5d4d82bdc5573bcb83db56f2c4bddc2596930b3e 100644 --- a/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_kit.cpp +++ b/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_kit.cpp @@ -1,42 +1,171 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "accesstoken_kit.h" - -#include -#include - -#include "accesstoken_log.h" -#include "accesstoken_manager_client.h" - -namespace OHOS { -namespace Security { -namespace AccessToken { -using namespace std; - -namespace { -static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenKit"}; -} // namespace - -int AccessTokenKit::VerifyAccesstoken(AccessTokenID tokenID, const std::string &permissionName) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s", - tokenID, permissionName.c_str()); - return AccessTokenManagerClient::GetInstance().VerifyAccesstoken(tokenID, permissionName); -} -} // namespace AccessToken -} // namespace Security -} // namespace OHOS \ No newline at end of file +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_kit.h" + +#include +#include + +#include "accesstoken_log.h" +#include "accesstoken_manager_client.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenKit"}; +} // namespace + +AccessTokenIDEx AccessTokenKit::AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + + return AccessTokenManagerClient::GetInstance().AllocHapToken(info, policy); +} + +AccessTokenID AccessTokenKit::AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + return AccessTokenManagerClient::GetInstance().AllocLocalTokenID(remoteDeviceID, remoteTokenID); +} + +int AccessTokenKit::UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParams& policy) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + return AccessTokenManagerClient::GetInstance().UpdateHapToken(tokenID, appIDDesc, policy); +} + +int AccessTokenKit::DeleteToken(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + + return AccessTokenManagerClient::GetInstance().DeleteToken(tokenID); +} + +int AccessTokenKit::GetTokenType(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + return AccessTokenManagerClient::GetInstance().GetTokenType(tokenID); +} + +int AccessTokenKit::CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, dcap=%{public}s", tokenID, dcap.c_str()); + return AccessTokenManagerClient::GetInstance().CheckNativeDCap(tokenID, dcap); +} + +AccessTokenID AccessTokenKit::GetHapTokenID(int userID, const std::string& bundleName, int instIndex) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "int userID=%{public}d, bundleName=%{public}s, instIndex=%{public}d", + userID, bundleName.c_str(), instIndex); + + return AccessTokenManagerClient::GetInstance().GetHapTokenID(userID, bundleName, instIndex); +} + +int AccessTokenKit::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + + return AccessTokenManagerClient::GetInstance().GetHapTokenInfo(tokenID, hapTokenInfoRes); +} + +int AccessTokenKit::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& nativeTokenInfoRes) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + + return AccessTokenManagerClient::GetInstance().GetNativeTokenInfo(tokenID, nativeTokenInfoRes); +} + +int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s", tokenID, permissionName.c_str()); + return AccessTokenManagerClient::GetInstance().VerifyAccessToken(tokenID, permissionName); +} + +int AccessTokenKit::VerifyAccessToken( + AccessTokenID callerTokenID, AccessTokenID firstTokenID, const std::string& permissionName) +{ + return 0; +} + +int AccessTokenKit::GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "permissionName=%{public}s", permissionName.c_str()); + + int ret = AccessTokenManagerClient::GetInstance().GetDefPermission(permissionName, permissionDefResult); + ACCESSTOKEN_LOG_INFO(LABEL, "GetDefPermission bundleName = %{public}s", permissionDefResult.bundleName.c_str()); + + return ret; +} + +int AccessTokenKit::GetDefPermissions(AccessTokenID tokenID, std::vector& permDefList) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + + ACCESSTOKEN_LOG_INFO(LABEL, "GetDefPermissions permDefList size = %{public}d", permDefList.size()); + return AccessTokenManagerClient::GetInstance().GetDefPermissions(tokenID, permDefList); +} + +int AccessTokenKit::GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, isSystemGrant=%{public}d", tokenID, isSystemGrant); + + ACCESSTOKEN_LOG_INFO(LABEL, "GetReqPermissions, reqPermList size=%{public}d", reqPermList.size()); + return AccessTokenManagerClient::GetInstance().GetReqPermissions(tokenID, reqPermList, isSystemGrant); +} + +int AccessTokenKit::GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s", tokenID, permissionName.c_str()); + return AccessTokenManagerClient::GetInstance().GetPermissionFlag(tokenID, permissionName); +} + +int AccessTokenKit::GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s, flag=%{public}d", + tokenID, permissionName.c_str(), flag); + return AccessTokenManagerClient::GetInstance().GrantPermission(tokenID, permissionName, flag); +} + +int AccessTokenKit::RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s, flag=%{public}d", + tokenID, permissionName.c_str(), flag); + return AccessTokenManagerClient::GetInstance().RevokePermission(tokenID, permissionName, flag); +} + +int AccessTokenKit::ClearUserGrantedPermissionState(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + return AccessTokenManagerClient::GetInstance().ClearUserGrantedPermissionState(tokenID); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_manager_client.cpp b/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_manager_client.cpp index a5de7d88eb882295421bdda5b6bed135a87ca48d..8f259f150ceeb3dfdf91c580a31223544fbd7b7b 100644 --- a/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_manager_client.cpp +++ b/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_manager_client.cpp @@ -16,8 +16,9 @@ #include "accesstoken_manager_client.h" #include "accesstoken_log.h" - +#include "hap_token_info.h" #include "iservice_registry.h" +#include "native_token_info.h" namespace OHOS { namespace Security { @@ -40,15 +41,225 @@ AccessTokenManagerClient::AccessTokenManagerClient() AccessTokenManagerClient::~AccessTokenManagerClient() {} -int AccessTokenManagerClient::VerifyAccesstoken(AccessTokenID tokenID, const std::string& permissionName) const +int AccessTokenManagerClient::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return RET_FAILED; + } + return proxy->VerifyAccessToken(tokenID, permissionName); +} + +int AccessTokenManagerClient::GetDefPermission( + const std::string& permissionName, PermissionDef& permissionDefResult) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return RET_FAILED; + } + PermissionDefParcel permissionDefParcel; + int result = proxy->GetDefPermission(permissionName, permissionDefParcel); + permissionDefResult = permissionDefParcel.permissionDef; + return result; +} + +int AccessTokenManagerClient::GetDefPermissions(AccessTokenID tokenID, std::vector& permList) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return RET_FAILED; + } + std::vector parcelList; + int result = proxy->GetDefPermissions(tokenID, parcelList); + for (auto permParcel : parcelList) { + PermissionDef perm = permParcel.permissionDef; + permList.emplace_back(perm); + } + return result; +} + +int AccessTokenManagerClient::GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return RET_FAILED; + } + std::vector parcelList; + int result = proxy->GetReqPermissions(tokenID, parcelList, isSystemGrant); + for (auto permParcel : parcelList) { + PermissionStateFull perm = permParcel.permStatFull; + reqPermList.emplace_back(perm); + } + return result; +} + +int AccessTokenManagerClient::GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return RET_FAILED; + } + return proxy->GetPermissionFlag(tokenID, permissionName); +} + +int AccessTokenManagerClient::GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return RET_FAILED; + } + return proxy->GrantPermission(tokenID, permissionName, flag); +} + +int AccessTokenManagerClient::RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return RET_FAILED; + } + return proxy->RevokePermission(tokenID, permissionName, flag); +} + +int AccessTokenManagerClient::ClearUserGrantedPermissionState(AccessTokenID tokenID) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return RET_FAILED; + } + return proxy->ClearUserGrantedPermissionState(tokenID); +} + +AccessTokenIDEx AccessTokenManagerClient::AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy) const +{ + AccessTokenIDEx res = { 0 }; + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return res; + } + HapInfoParcel hapInfoParcel; + HapPolicyParcel hapPolicyParcel; + hapInfoParcel.hapInfoParameter = info; + hapPolicyParcel.hapPolicyParameter = policy; + + return proxy->AllocHapToken(hapInfoParcel, hapPolicyParcel); +} + +int AccessTokenManagerClient::DeleteToken(AccessTokenID tokenID) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return RET_FAILED; + } + return proxy->DeleteToken(tokenID); +} + +int AccessTokenManagerClient::GetTokenType(AccessTokenID tokenID) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return RET_FAILED; + } + return proxy->GetTokenType(tokenID); +} + +int AccessTokenManagerClient::CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return RET_FAILED; + } + return proxy->CheckNativeDCap(tokenID, dcap); +} + +AccessTokenID AccessTokenManagerClient::GetHapTokenID(int userID, const std::string& bundleName, int instIndex) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return RET_FAILED; + } + return proxy->GetHapTokenID(userID, bundleName, instIndex); +} + +AccessTokenID AccessTokenManagerClient::AllocLocalTokenID( + const std::string& remoteDeviceID, AccessTokenID remoteTokenID) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return RET_FAILED; + } + return proxy->AllocLocalTokenID(remoteDeviceID, remoteTokenID); +} + +int AccessTokenManagerClient::UpdateHapToken( + AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParams& policy) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return RET_FAILED; + } + HapPolicyParcel hapPolicyParcel; + hapPolicyParcel.hapPolicyParameter = policy; + return proxy->UpdateHapToken(tokenID, appIDDesc, hapPolicyParcel); +} + +int AccessTokenManagerClient::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return RET_FAILED; + } + HapTokenInfoParcel hapTokenInfoParcel; + int res = proxy->GetHapTokenInfo(tokenID, hapTokenInfoParcel); + + hapTokenInfoRes = hapTokenInfoParcel.hapTokenInfoParams; + return res; +} + +int AccessTokenManagerClient::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& nativeTokenInfoRes) const { ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); - return PERMISSION_DENIED; + return RET_FAILED; } - return proxy->VerifyAccesstoken(tokenID, permissionName); + NativeTokenInfoParcel nativeTokenInfoParcel; + int res = proxy->GetNativeTokenInfo(tokenID, nativeTokenInfoParcel); + nativeTokenInfoRes = nativeTokenInfoParcel.nativeTokenInfoParams; + return res; } sptr AccessTokenManagerClient::GetProxy() const @@ -74,4 +285,4 @@ sptr AccessTokenManagerClient::GetProxy() const } } // namespace AccessToken } // namespace Security -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_manager_client.h b/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_manager_client.h index 758e6f59845c8e89cb35b70631ef84390d8efa91..cedcdae1086c94fb5a8b7a6d82f435fe925184b9 100755 --- a/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_manager_client.h +++ b/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_manager_client.h @@ -17,9 +17,17 @@ #define ACCESSTOKEN_MANAGER_CLIENT_H #include +#include +#include "access_token.h" +#include "hap_info_parcel.h" +#include "hap_policy_parcel.h" +#include "hap_token_info.h" #include "i_accesstoken_manager.h" +#include "native_token_info.h" #include "nocopyable.h" +#include "permission_def.h" +#include "permission_state_full.h" namespace OHOS { namespace Security { @@ -30,7 +38,25 @@ public: virtual ~AccessTokenManagerClient(); - int VerifyAccesstoken(AccessTokenID tokenID, const std::string& permissionName) const; + int VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) const; + int GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult) const; + int GetDefPermissions(AccessTokenID tokenID, std::vector& permList) const; + int GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) const; + int GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) const; + int GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) const; + int RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) const; + int ClearUserGrantedPermissionState(AccessTokenID tokenID) const; + AccessTokenIDEx AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy) const; + int DeleteToken(AccessTokenID tokenID) const; + int GetTokenType(AccessTokenID tokenID) const; + int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) const; + AccessTokenID GetHapTokenID(int userID, const std::string& bundleName, int instIndex) const; + AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID) const; + int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParams& policy) const; + int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes) const; + int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& nativeTokenInfoRes) const; + private: AccessTokenManagerClient(); diff --git a/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_manager_proxy.cpp b/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_manager_proxy.cpp index ce8d6ec7f793bf28900da3a21276e24233863a88..e031e8c025d46d67bca37119127bdd6baeb92210 100644 --- a/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_manager_proxy.cpp +++ b/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_manager_proxy.cpp @@ -28,13 +28,13 @@ static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ } AccessTokenManagerProxy::AccessTokenManagerProxy(const sptr& impl) - : IRemoteProxy(impl) -{} + : IRemoteProxy(impl) { +} AccessTokenManagerProxy::~AccessTokenManagerProxy() {} -int AccessTokenManagerProxy::VerifyAccesstoken(AccessTokenID tokenID, const std::string& permissionName) +int AccessTokenManagerProxy::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) { MessageParcel data; data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); @@ -66,6 +66,547 @@ int AccessTokenManagerProxy::VerifyAccesstoken(AccessTokenID tokenID, const std: return result; } +int AccessTokenManagerProxy::GetDefPermission( + const std::string& permissionName, PermissionDefParcel& permissionDefResult) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteString(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_DEF_PERMISSION), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return RET_FAILED; + } + + sptr resultSptr = reply.ReadParcelable(); + if (resultSptr == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s ReadParcelable fail", __func__); + return RET_FAILED; + } + permissionDefResult = *resultSptr; + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +int AccessTokenManagerProxy::GetDefPermissions(AccessTokenID tokenID, + std::vector& permList) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_DEF_PERMISSIONS), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return RET_FAILED; + } + + int32_t size = reply.ReadInt32(); + for (int i = 0; i < size; i++) { + sptr permissionDef = reply.ReadParcelable(); + if (permissionDef != nullptr) { + permList.emplace_back(*permissionDef); + } + } + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +int AccessTokenManagerProxy::GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + return RET_FAILED; + } + if (!data.WriteInt32(isSystemGrant)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write isSystemGrant", __func__); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_REQ_PERMISSIONS), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return RET_FAILED; + } + + int32_t size = reply.ReadInt32(); + for (int i = 0; i < size; i++) { + sptr permissionReq = reply.ReadParcelable(); + if (permissionReq != nullptr) { + reqPermList.emplace_back(*permissionReq); + } + } + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +int AccessTokenManagerProxy::GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + return RET_FAILED; + } + if (!data.WriteString(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_PERMISSION_FLAG), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +int AccessTokenManagerProxy::GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + return RET_FAILED; + } + if (!data.WriteString(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__); + return RET_FAILED; + } + if (!data.WriteInt32(flag)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write flag", __func__); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GRANT_PERMISSION), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +int AccessTokenManagerProxy::RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + return RET_FAILED; + } + if (!data.WriteString(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__); + return RET_FAILED; + } + if (!data.WriteInt32(flag)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write flag", __func__); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::REVOKE_PERMISSION), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +int AccessTokenManagerProxy::ClearUserGrantedPermissionState(AccessTokenID tokenID) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::CLEAR_USER_GRANT_PERMISSION), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +AccessTokenIDEx AccessTokenManagerProxy::AllocHapToken( + const HapInfoParcel& hapInfo, const HapPolicyParcel& policyParcel) +{ + MessageParcel data; + AccessTokenIDEx res; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + + if (!data.WriteParcelable(&hapInfo)) { + res.tokenIDEx = 0; + return res; + } + if (!data.WriteParcelable(&policyParcel)) { + res.tokenIDEx = 0; + return res; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + res.tokenIDEx = 0; + return res; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::ALLOC_TOKEN_HAP), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + res.tokenIDEx = 0; + return res; + } + + uint64_t result = reply.ReadUint64(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}llu", __func__, result); + res.tokenIDEx = result; + return res; +} + +int AccessTokenManagerProxy::DeleteToken(AccessTokenID tokenID) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::TOKEN_DELETE), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return RET_FAILED; + } + + int result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +int AccessTokenManagerProxy::GetTokenType(AccessTokenID tokenID) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_TOKEN_TYPE), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return RET_FAILED; + } + + int result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +int AccessTokenManagerProxy::CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + return RET_FAILED; + } + if (!data.WriteString(dcap)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write dcap", __func__); + return RET_FAILED; + } + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::CHECK_NATIVE_DCAP), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return RET_FAILED; + } + + int result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +AccessTokenID AccessTokenManagerProxy::GetHapTokenID(int userID, const std::string& bundleName, int instIndex) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + + if (!data.WriteInt32(userID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + return 0; + } + if (!data.WriteString(bundleName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write dcap", __func__); + return 0; + } + if (!data.WriteInt32(instIndex)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write dcap", __func__); + return 0; + } + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return 0; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_HAP_TOKEN_ID), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return 0; + } + + int result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +AccessTokenID AccessTokenManagerProxy::AllocLocalTokenID( + const std::string& remoteDeviceID, AccessTokenID remoteTokenID) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + + if (!data.WriteString(remoteDeviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write dcap", __func__); + return 0; + } + if (!data.WriteUint32(remoteTokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write dcap", __func__); + return 0; + } + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return 0; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::ALLOC_LOCAL_TOKEN_ID), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return 0; + } + + AccessTokenID result = reply.ReadUint32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +int AccessTokenManagerProxy::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfoParcel& nativeTokenInfoRes) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_NATIVE_TOKENINFO), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return RET_FAILED; + } + + sptr resultSptr = reply.ReadParcelable(); + if (resultSptr == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s ReadParcelable fail", __func__); + return RET_FAILED; + } + nativeTokenInfoRes = *resultSptr; + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +int AccessTokenManagerProxy::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfoParcel& hapTokenInfoRes) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_HAP_TOKENINFO), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return RET_FAILED; + } + + sptr resultSptr = reply.ReadParcelable(); + if (resultSptr == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s ReadParcelable fail", __func__); + return RET_FAILED; + } + hapTokenInfoRes = *resultSptr; + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +int AccessTokenManagerProxy::UpdateHapToken(AccessTokenID tokenID, + const std::string& appIDDesc, const HapPolicyParcel& policyParcel) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + return RET_FAILED; + } + if (!data.WriteString(appIDDesc)) { + return RET_FAILED; + } + if (!data.WriteParcelable(&policyParcel)) { + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::UPDATE_HAP_TOKEN), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + return result; +} } // namespace AccessToken } // namespace Security -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_manager_proxy.h b/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_manager_proxy.h index e0c99c62dc48c7f9c5f9b51106077cb0d4e33a64..9737147025553c2de865d677247bacc2b9faed5f 100644 --- a/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_manager_proxy.h +++ b/interfaces/innerkits/accesstoken/main/cpp/src/accesstoken_manager_proxy.h @@ -16,9 +16,18 @@ #ifndef ACCESSTOKEN_MANAGER_PROXY_H #define ACCESSTOKEN_MANAGER_PROXY_H -#include "i_accesstoken_manager.h" +#include +#include +#include "access_token.h" +#include "hap_info_parcel.h" +#include "hap_policy_parcel.h" +#include "hap_token_info_parcel.h" +#include "i_accesstoken_manager.h" #include "iremote_proxy.h" +#include "native_token_info_parcel.h" +#include "permission_def_parcel.h" +#include "permission_state_full_parcel.h" namespace OHOS { namespace Security { @@ -28,7 +37,25 @@ public: explicit AccessTokenManagerProxy(const sptr& impl); virtual ~AccessTokenManagerProxy() override; - int VerifyAccesstoken(AccessTokenID tokenID, const std::string& permissionName) override; + int VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) override; + int GetDefPermission(const std::string& permissionName, PermissionDefParcel& permissionDefResult) override; + int GetDefPermissions(AccessTokenID tokenID, std::vector& permList) override; + int GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) override; + int GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) override; + int GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) override; + int RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) override; + int ClearUserGrantedPermissionState(AccessTokenID tokenID) override; + int GetTokenType(AccessTokenID tokenID) override; + int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) override; + AccessTokenID GetHapTokenID(int userID, const std::string& bundleName, int instIndex) override; + AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID) override; + AccessTokenIDEx AllocHapToken(const HapInfoParcel& hapInfo, const HapPolicyParcel& policyParcel) override; + int DeleteToken(AccessTokenID tokenID) override; + int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, + const HapPolicyParcel& policyPar) override; + int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfoParcel& hapTokenInfoRes) override; + int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfoParcel& nativeTokenInfoRes) override; private: static inline BrokerDelegator delegator_; }; diff --git a/interfaces/innerkits/accesstoken/test/BUILD.gn b/interfaces/innerkits/accesstoken/test/BUILD.gn index a61294493aa5b096203ec73b1f644abca06eb99a..fed32567e96d179dfebb8307f1f7d826aec8fbc9 100755 --- a/interfaces/innerkits/accesstoken/test/BUILD.gn +++ b/interfaces/innerkits/accesstoken/test/BUILD.gn @@ -20,7 +20,8 @@ ohos_unittest("libaccesstoken_sdk_test") { include_dirs = [ "//utils/native/base/include", - "//base/security/access_token/interfaces/innerkits/accesstoken/main/cpp/include/", + "//third_party/googletest/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/main/cpp/include" ] sources = [ "unittest/cpp/src/accesstoken_kit_test.cpp" ] diff --git a/interfaces/innerkits/accesstoken/test/unittest/cpp/src/accesstoken_kit_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/cpp/src/accesstoken_kit_test.cpp index 7fbf82406a97720a7a04c6b8de520cacbc67b662..cce73330e8752b833d29957f1f146311a1459549 100755 --- a/interfaces/innerkits/accesstoken/test/unittest/cpp/src/accesstoken_kit_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/cpp/src/accesstoken_kit_test.cpp @@ -24,26 +24,285 @@ void AccessTokenKitTest::SetUpTestCase() {} void AccessTokenKitTest::TearDownTestCase() -{} +{ +} void AccessTokenKitTest::SetUp() -{} +{ + HapInfoParams info = { + .userID = TEST_USER_ID, + .bundleName = TEST_BUNDLE_NAME, + .instIndex = 0, + .appIDDesc = "appIDDesc", + }; + HapPolicyParams policy = { + .apl = APL_NORMAL, + .domain = "domain" + }; + + PermissionDef permissionDefAlpha = { + .permissionName = TEST_PERMISSION_NAME_ALPHA, + .bundleName = TEST_BUNDLE_NAME, + .grantMode = GrantMode::USER_GRANT, + .availableScope = AVAILABLE_SCOPE_ALL, + }; + + PermissionDef permissionDefBeta = { + .permissionName = TEST_PERMISSION_NAME_BETA, + .bundleName = TEST_BUNDLE_NAME, + .grantMode = GrantMode::SYSTEM_GRANT, + .availableScope = AVAILABLE_SCOPE_ALL, + }; + policy.permList.emplace_back(permissionDefAlpha); + policy.permList.emplace_back(permissionDefBeta); + + PermissionStateFull permStatAlpha = { + .permissionName = TEST_PERMISSION_NAME_ALPHA, + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, + .grantFlags = {PermissionFlag::PERMISSION_USER_SET} + }; + PermissionStateFull permStatBeta = { + .permissionName = TEST_PERMISSION_NAME_BETA, + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .grantFlags = {PermissionFlag::PERMISSION_USER_SET} + }; + policy.permStateList.emplace_back(permStatAlpha); + policy.permStateList.emplace_back(permStatBeta); + + AccessTokenKit::AllocHapToken(info, policy); +} void AccessTokenKitTest::TearDown() -{} +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + AccessTokenKit::DeleteToken(tokenID); +} + +unsigned int AccessTokenKitTest::GetAccessTokenID(int userID, std::string bundleName, int instIndex) +{ + return AccessTokenKit::GetHapTokenID(userID, bundleName, instIndex); +} +/** + * @tc.name: AllocHapToken001 + * @tc.desc: Get permission definition info after AllocHapToken function has been invoked. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken001, TestSize.Level1) +{ + PermissionDef permDefResultAlpha; + int ret = AccessTokenKit::GetDefPermission(TEST_PERMISSION_NAME_ALPHA, permDefResultAlpha); + ASSERT_EQ(TEST_PERMISSION_NAME_ALPHA, permDefResultAlpha.permissionName); + ASSERT_EQ(RET_SUCCESS, ret); + + PermissionDef permDefResultBeta; + ret = AccessTokenKit::GetDefPermission(TEST_PERMISSION_NAME_BETA, permDefResultBeta); + ASSERT_EQ(TEST_PERMISSION_NAME_BETA, permDefResultBeta.permissionName); + ASSERT_EQ(RET_SUCCESS, ret); +} + +/** + * @tc.name: AllocHapToken002 + * @tc.desc: Get permission definition info that permission is not exist. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken002, TestSize.Level1) +{ + PermissionDef permDefResult; + int ret = AccessTokenKit::GetDefPermission(TEST_PERMISSION_NAME_GAMMA, permDefResult); + ASSERT_EQ(RET_FAILED, ret); +} /** - * @tc.name: VerifyAccesstoken001 - * @tc.desc: Verify user granted permission + * @tc.name: AllocHapToken003 + * @tc.desc: Get permission definition info list after AllocHapToken function has been invoked. * @tc.type: FUNC * @tc.require: */ -HWTEST_F(AccessTokenKitTest, VerifyAccesstoken001, TestSize.Level0) +HWTEST_F(AccessTokenKitTest, AllocHapToken003, TestSize.Level1) { - AccessTokenID tokenID = 1; - const std::string TEST_PERMISSION_NAME = "ohos.permission.TEST"; + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + std::vector permDefList; + int ret = AccessTokenKit::GetDefPermissions(tokenID, permDefList); + ASSERT_EQ(RET_SUCCESS, ret); + ASSERT_EQ(2, permDefList.size()); +} - int ret = AccessTokenKit::VerifyAccesstoken(tokenID, TEST_PERMISSION_NAME); +/** + * @tc.name: AllocHapToken004 + * @tc.desc: Get permission definition info list that tokenID is invalid. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken004, TestSize.Level1) +{ + std::vector permDefList; + int ret = AccessTokenKit::GetDefPermissions(TEST_TOKENID_INVALID, permDefList); + ASSERT_EQ(RET_FAILED, ret); +} + +/** + * @tc.name: GetReqPermissions001 + * @tc.desc: Get user granted permission state info. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AccessTokenKitTest, GetReqPermissions001, TestSize.Level1) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + std::vector permStatList; + int ret = AccessTokenKit::GetReqPermissions(tokenID, permStatList, false); + ASSERT_EQ(RET_SUCCESS, ret); + ASSERT_EQ(1, permStatList.size()); + ASSERT_EQ(TEST_PERMISSION_NAME_ALPHA, permStatList[0].permissionName); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(ret, permStatList[0].grantStatus[0]); +} + +/** + * @tc.name: GetReqPermissions002 + * @tc.desc: Get system granted permission state info. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AccessTokenKitTest, GetReqPermissions002, TestSize.Level1) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + std::vector permStatList; + int ret = AccessTokenKit::GetReqPermissions(tokenID, permStatList, true); + ASSERT_EQ(RET_SUCCESS, ret); + ASSERT_EQ(1, permStatList.size()); + ASSERT_EQ(TEST_PERMISSION_NAME_BETA, permStatList[0].permissionName); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_BETA); + ASSERT_EQ(ret, permStatList[0].grantStatus[0]); +} + +/** + * @tc.name: GetPermissionFlag001 + * @tc.desc: Get permission flag after grant permission. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AccessTokenKitTest, GetPermissionFlag001, TestSize.Level1) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + int ret = AccessTokenKit::GrantPermission(tokenID, TEST_PERMISSION_NAME_ALPHA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::GetPermissionFlag(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_USER_FIXED, ret); +} + +/** + * @tc.name: VerifyAccessToken001 + * @tc.desc: Verify user granted permission. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AccessTokenKitTest, VerifyAccessToken001, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + int ret = AccessTokenKit::GrantPermission(tokenID, TEST_PERMISSION_NAME_ALPHA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_GRANTED, ret); + + ret = AccessTokenKit::RevokePermission(tokenID, TEST_PERMISSION_NAME_ALPHA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_DENIED, ret); +} + +/** + * @tc.name: VerifyAccessToken002 + * @tc.desc: Verify system granted permission. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AccessTokenKitTest, VerifyAccessToken002, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + int ret = AccessTokenKit::GrantPermission(tokenID, TEST_PERMISSION_NAME_BETA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_BETA); ASSERT_EQ(PERMISSION_GRANTED, ret); -} \ No newline at end of file + ret = AccessTokenKit::RevokePermission(tokenID, TEST_PERMISSION_NAME_BETA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_BETA); + ASSERT_EQ(PERMISSION_DENIED, ret); +} + +/** + * @tc.name: VerifyAccessToken003 + * @tc.desc: Verify permission that has not been defined. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AccessTokenKitTest, VerifyAccessToken003, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + int ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_GAMMA); + ASSERT_EQ(PERMISSION_DENIED, ret); +} + +/** + * @tc.name: ClearUserGrantedPermissionState001 + * @tc.desc: Clear user granted permission fater ClearUserGrantedPermissionState has been invoked. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AccessTokenKitTest, ClearUserGrantedPermissionState001, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + int ret = AccessTokenKit::ClearUserGrantedPermissionState(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_DENIED, ret); +} + +/** + * @tc.name: DeleteToken001 + * @tc.desc: Cannot get permission definition info after DeleteToken function has been invoked. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AccessTokenKitTest, DeleteToken001, TestSize.Level1) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + PermissionDef permDefResultAlpha; + int ret = AccessTokenKit::GetDefPermission(TEST_PERMISSION_NAME_ALPHA, permDefResultAlpha); + ASSERT_EQ(TEST_PERMISSION_NAME_ALPHA, permDefResultAlpha.permissionName); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + + PermissionDef defResult; + ret = AccessTokenKit::GetDefPermission(TEST_PERMISSION_NAME_ALPHA, defResult); + ASSERT_EQ(RET_FAILED, ret); +} + +/** + * @tc.name: DeleteToken002 + * @tc.desc: Delete invalid tokenID. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AccessTokenKitTest, DeleteToken002, TestSize.Level1) +{ + int ret = AccessTokenKit::DeleteToken(TEST_USER_ID_INVALID); + ASSERT_EQ(RET_FAILED, ret); +} diff --git a/interfaces/innerkits/accesstoken/test/unittest/cpp/src/accesstoken_kit_test.h b/interfaces/innerkits/accesstoken/test/unittest/cpp/src/accesstoken_kit_test.h index 5784ad6f4cccb0584a0794179a4b32e6de6212c6..25de97777f62a265f66b7da8e7911faa359495fd 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/cpp/src/accesstoken_kit_test.h +++ b/interfaces/innerkits/accesstoken/test/unittest/cpp/src/accesstoken_kit_test.h @@ -21,6 +21,13 @@ namespace OHOS { namespace Security { namespace AccessToken { +static const std::string TEST_BUNDLE_NAME = "ohos"; +static const std::string TEST_PERMISSION_NAME_ALPHA = "ohos.permission.ALPHA"; +static const std::string TEST_PERMISSION_NAME_BETA = "ohos.permission.BETA"; +static const std::string TEST_PERMISSION_NAME_GAMMA = "ohos.permission.GAMMA"; +static const int TEST_USER_ID = 0; +static const int TEST_USER_ID_INVALID = -1; +static const unsigned int TEST_TOKENID_INVALID = 0; class AccessTokenKitTest : public testing::Test { public: static void SetUpTestCase(); @@ -30,6 +37,7 @@ public: void SetUp(); void TearDown(); + unsigned int GetAccessTokenID(int userID, std::string bundleName, int instIndex); }; } // namespace AccessToken } // namespace Security diff --git a/interfaces/innerkits/atlib/BUILD.gn b/interfaces/innerkits/atlib/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..29099e670ad8d321e457f6b211fdc347261b8f57 --- /dev/null +++ b/interfaces/innerkits/atlib/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +################################################################ +# C, Main, source file here. +################################################################ +config("accesstokenlib") { + visibility = [ ":*" ] + include_dirs = [ "main/include" ] +} + +ohos_shared_library("libaccesstoken_lib") { + subsystem_name = "security" + part_name = "access_token" + output_name = "libaccesstoken_lib" + + public_configs = [ ":accesstokenlib" ] + + cflags = [ "-Wall" ] + + include_dirs = [ + "//utils/native/base/include", + "main/include", + "main/src", + "//third_party/cJSON", + "//third_party/bounds_checking_function/include", + "//base/hiviewdfx/hilog_lite/interfaces/native/kits", + ] + + sources = [ + "main/src/accesstoken_lib.c", + ] + + deps = [ + "//utils/native/base:utils", + "//third_party/cJSON:cjson_static", + "//utils/native/base:utilsecurec_shared", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + ] +} diff --git a/interfaces/innerkits/atlib/main/include/accesstoken_lib.h b/interfaces/innerkits/atlib/main/include/accesstoken_lib.h new file mode 100644 index 0000000000000000000000000000000000000000..da37447118b727d4d3f5bea57060b0dc4fc9b725 --- /dev/null +++ b/interfaces/innerkits/atlib/main/include/accesstoken_lib.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing ACCESSTOKENs and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "cJSON.h" +#include "securec.h" +#include "accesstoken_log.h" + +#ifndef ACCESSTOKEN_LIB_H +#define ACCESSTOKEN_LIB_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define MAX_PROCESS_NAME_LEN 256 +#define TOKEN_ID_CFG_PATH "/data/token.json" +#define SOCKET_FILE "/data/token_unix_socket" +#define ERR 1 +#define SUCCESS 0 +#define TOKEN_NATIVE_TYPE 1 +#define DEFAULT_AT_VERSION 1 +#define TRANSFER_KEY_WORDS "NativeTokenInfo" +#define MAX_JSON_FILE_LEN 102400 + +typedef unsigned int NativeAtId; +typedef unsigned int NativeAtAttr; + +typedef struct { + unsigned int tokenUniqueId : 24; + unsigned int reserved : 3; + unsigned int type : 2; + unsigned int version : 3; +} AtInnerInfo; + +typedef struct { + NativeAtId tokenId; + NativeAtAttr tokenAttr; +} NativeAtIdEx; + +typedef struct TokenList { + NativeAtId tokenId; + char processName[MAX_PROCESS_NAME_LEN]; + struct TokenList *next; +} NativeTokenList; + +typedef struct TokenQueue { + NativeAtId tokenId; + int apl; + const char *processName; + const char **dcaps; + int dcapsNum; + int flag; + struct TokenQueue *next; +} NativeTokenQueue; + +#define TOKEN_QUEUE_NODE_INFO_SET(tmp, aplStr, processname, tokenId, exist, dcap, dacpNum) do { \ + (tmp).apl = GetAplLevel((aplStr)); \ + (tmp).processName = (processname); \ + (tmp).tokenId = (tokenId); \ + (tmp).flag = (exist); \ + (tmp).dcaps = (dcap); \ + (tmp).dcapsNum = (dacpNum); \ +} while (0) + +extern void *ThreadTransferFunc(const void *args); + +#ifdef __cplusplus +} +#endif + +#endif // ACCESSTOKEN_LIB_H diff --git a/interfaces/innerkits/atlib/main/include/accesstoken_log.h b/interfaces/innerkits/atlib/main/include/accesstoken_log.h new file mode 100644 index 0000000000000000000000000000000000000000..cdf5fa761840922ab558017cb9a08e202e77f755 --- /dev/null +++ b/interfaces/innerkits/atlib/main/include/accesstoken_log.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing ACCESSTOKENs and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_LOG_H +#define ACCESSTOKEN_LOG_H + +#ifdef HILOG_ENABLE + +#include "hilog/log.h" + +#define ACCESSTOKEN_LOG_DEBUG(fmt, ...) HILOG_DEBUG(LOG_CORE, fmt, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_INFO(fmt, ...) HILOG_INFO(LOG_CORE, fmt, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_WARN(fmt, ...) HILOG_WARN(LOG_CORE, fmt, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_ERROR(fmt, ...) ACCESSTOKEN_LOG_ERROR(LOG_CORE, fmt, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_FATAL(fmt, ...) HILOG_FATAL(LOG_CORE, fmt, ##__VA_ARGS__) + +/* define LOG_TAG as "security_*" at your submodule, * means your submodule name such as "security_dac" */ +#undef LOG_TAG +#undef LOG_DOMAIN + +#else + +#include +#include + +/* define LOG_TAG as "security_*" at your submodule, * means your submodule name such as "security_dac" */ +#define LOG_TAG "accssToken_" + +#define ACCESSTOKEN_LOG_DEBUG(fmt, ...) printf("[%s] debug: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_INFO(fmt, ...) printf("[%s] info: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_WARN(fmt, ...) printf("[%s] warn: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_ERROR(fmt, ...) printf("[%s] error: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_FATAL(fmt, ...) printf("[%s] fatal: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) + +#endif // HILOG_ENABLE + +#endif // ACCESSTOKEN_LOG_H diff --git a/interfaces/innerkits/atlib/main/include/accesstokenlib_kit.h b/interfaces/innerkits/atlib/main/include/accesstokenlib_kit.h new file mode 100644 index 0000000000000000000000000000000000000000..d0511410ec647e910583e879c222b8af494f8732 --- /dev/null +++ b/interfaces/innerkits/atlib/main/include/accesstokenlib_kit.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_ACCESSTOKEN_LIB_H +#define INTERFACES_INNER_KITS_ACCESSTOKEN_LIB_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +extern int32_t AtlibInit(void); + +extern uint64_t GetAccessTokenId(const char *processname, const char **dcap, int32_t dacpNum, const char *aplStr); + +#ifdef __cplusplus +} +#endif + +#endif // INTERFACES_INNER_KITS_ACCESSTOKEN_LIB_H diff --git a/interfaces/innerkits/atlib/main/src/accesstoken_lib.c b/interfaces/innerkits/atlib/main/src/accesstoken_lib.c new file mode 100644 index 0000000000000000000000000000000000000000..7a921900ee11fce8eb03420afeceba6ae03a30a1 --- /dev/null +++ b/interfaces/innerkits/atlib/main/src/accesstoken_lib.c @@ -0,0 +1,514 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing ACCESSTOKENs and + * limitations under the License. + */ + +#include "accesstoken_lib.h" +#include "accesstokenlib_kit.h" + +NativeTokenQueue *g_tokenQueueHead; +NativeTokenList *g_tokenListHead; +int g_isAtmExist; +int g_signalFd; +static pthread_mutex_t g_tokenQueueHeadLock = PTHREAD_MUTEX_INITIALIZER; + +char *GetFileBuff(const char *cfg) +{ + char *buff = NULL; + FILE *cfgFd = NULL; + struct stat fileStat; + int fileSize; + + if (stat(cfg, &fileStat) != 0) { + ACCESSTOKEN_LOG_ERROR("stat file failed."); + return NULL; + } + fileSize = (int)fileStat.st_size; + if ((fileSize < 0) || (fileSize > MAX_JSON_FILE_LEN)) { + ACCESSTOKEN_LOG_ERROR("stat file size is invalid."); + return NULL; + } + + cfgFd = fopen(cfg, "r"); + if (cfgFd == NULL) { + ACCESSTOKEN_LOG_ERROR("fopen file failed."); + return NULL; + } + + buff = (char *)malloc((size_t)(fileSize + 1)); + if (buff == NULL) { + ACCESSTOKEN_LOG_ERROR("memory alloc failed."); + fclose(cfgFd); + return NULL; + } + + if (fread(buff, fileSize, 1, cfgFd) != 1) { + ACCESSTOKEN_LOG_ERROR("fread failed."); + free(buff); + buff = NULL; + } else { + buff[fileSize] = '\0'; + } + + fclose(cfgFd); + return buff; +} + +int GetTokenList(const cJSON *object) +{ + if (object == NULL) { + return ERR; + } + int arraySize = cJSON_GetArraySize(object); + + for (int i = 0; i < arraySize; i++) { + cJSON *cjsonItem = cJSON_GetArrayItem(object, i); + cJSON *processNameJson = cJSON_GetObjectItem(cjsonItem, "processName"); + cJSON *tokenIdJson = cJSON_GetObjectItem(cjsonItem, "tokenId"); + if (cJSON_IsString(processNameJson) == 0 || (strlen(processNameJson->valuestring) > MAX_PROCESS_NAME_LEN)) { + ACCESSTOKEN_LOG_ERROR("processNameJson is invalid."); + return ERR; + } + if ((cJSON_IsNumber(tokenIdJson) == 0) || (cJSON_GetNumberValue(tokenIdJson) <= 0)) { + ACCESSTOKEN_LOG_ERROR("tokenIdJson is invalid."); + return ERR; + } + + NativeTokenList *tmp = (NativeTokenList *)malloc(sizeof(NativeTokenList)); + if (tmp == NULL) { + ACCESSTOKEN_LOG_ERROR("memory alloc failed."); + return ERR; + } + (void)strcpy_s(tmp->processName, MAX_PROCESS_NAME_LEN, processNameJson->valuestring); + tmp->tokenId = tokenIdJson->valueint; + tmp->next = g_tokenListHead->next; + g_tokenListHead->next = tmp; + } + return SUCCESS; +} + +int ParseTokenInfoCfg(const char *filename) +{ + char *fileBuff; + cJSON *record; + int ret; + + if (filename == NULL || filename[0] == '\0') { + return ERR; + } + fileBuff = GetFileBuff(filename); + if (fileBuff == NULL) { + return ERR; + } + record = cJSON_Parse(fileBuff); + free(fileBuff); + fileBuff = NULL; + + ret = GetTokenList(record); + cJSON_Delete(record); + + return ret; +} + +int AtlibInit(void) +{ + g_tokenListHead = (NativeTokenList *)malloc(sizeof(NativeTokenList)); + if (g_tokenListHead == NULL) { + ACCESSTOKEN_LOG_ERROR("g_tokenListHead memory alloc failed."); + return ERR; + } + g_tokenListHead->next = NULL; + + g_tokenQueueHead = (NativeTokenQueue *)malloc(sizeof(NativeTokenQueue)); + if (g_tokenQueueHead == NULL) { + free(g_tokenListHead); + ACCESSTOKEN_LOG_ERROR("g_tokenQueueHead memory alloc failed."); + return ERR; + } + g_tokenQueueHead->next = NULL; + g_isAtmExist = 0; + + return ParseTokenInfoCfg(TOKEN_ID_CFG_PATH); +} + +int GetRandomTokenId(unsigned int *randNum) +{ + unsigned int random; + int len; + int fd = open("/dev/urandom", O_RDONLY); + if (fd == -1) { + return ERR; + } + len = read(fd, &random, sizeof(random)); + (void)close(fd); + if (len != sizeof(random)) { + ACCESSTOKEN_LOG_ERROR("read failed."); + return ERR; + } + *randNum = random; + return SUCCESS; +} + +NativeAtId CreateNativeTokenId(const char *processName) +{ + unsigned int rand; + NativeAtId tokenId; + AtInnerInfo *innerId = (AtInnerInfo *)(&tokenId); + + if (GetRandomTokenId(&rand) == ERR) { + return 0; + } + + innerId->reserved = 0; + innerId->tokenUniqueId = rand & (0xFFFFFF); + innerId->type = TOKEN_NATIVE_TYPE; + innerId->version = 1; + return tokenId; +} + +int TriggerTransfer() +{ + int ret; + static const uint64_t increment = 1; + ret = write(g_signalFd, &increment, sizeof(increment)); + if (ret == -1) { + ACCESSTOKEN_LOG_ERROR("TriggerTransfer write failed."); + return ERR; + } + return SUCCESS; +} + +int TokenInfoSave(const NativeTokenQueue *node) +{ + if (node->apl == 0) { + return ERR; + } + NativeTokenQueue *curr; + curr = (NativeTokenQueue *)malloc(sizeof(NativeTokenQueue)); + if (curr == NULL) { + ACCESSTOKEN_LOG_ERROR("memory alloc failed."); + return ERR; + } + curr->apl = node->apl; + curr->processName = node->processName; + curr->tokenId = node->tokenId; + curr->flag = node->flag; + curr->dcaps = node->dcaps; + curr->dcapsNum = node->dcapsNum; + + pthread_mutex_lock(&g_tokenQueueHeadLock); + curr->next = g_tokenQueueHead->next; + g_tokenQueueHead->next = curr; + pthread_mutex_unlock(&g_tokenQueueHeadLock); + + if (g_isAtmExist == 1) { + return TriggerTransfer(); + } + return SUCCESS; +} + +int GetAplLevel(const char *aplStr) +{ + if (strcmp(aplStr, "system_core") == 0) { + return 3; // system_core means apl level is 3 + } + if (strcmp(aplStr, "system_basic") == 0) { + return 2; // system_basic means apl level is 2 + } + if (strcmp(aplStr, "normal") == 0) { + return 1; + } + return 0; +} + +uint64_t GetAccessTokenId(const char *processname, const char **dcap, int dacpNum, const char *aplStr) +{ + NativeAtId tokenId; + NativeTokenList *tokenNode = g_tokenListHead; + NativeTokenQueue tmp; + + int exist = 0; + int ret; + uint64_t result = 0; + NativeAtIdEx *atPoint = (NativeAtIdEx *)(&result); + + while (tokenNode != NULL) { + if (strcmp(tokenNode->processName, processname) == 0) { + exist = 1; + tokenId = tokenNode->tokenId; + break; + } + tokenNode = tokenNode->next; + } + + if (exist == 0) { + tokenId = CreateNativeTokenId(processname); + tokenNode = (NativeTokenList *)malloc(sizeof(NativeTokenList)); + if (tokenNode == NULL) { + ACCESSTOKEN_LOG_ERROR("memory alloc failed."); + return 0; + } + (void)strcpy_s(tokenNode->processName, MAX_PROCESS_NAME_LEN, processname); + tokenNode->tokenId = tokenId; + tokenNode->next = g_tokenListHead->next; + g_tokenListHead->next = tokenNode; + ACCESSTOKEN_LOG_INFO("tokenNode->tokenId :%d, tokenNode->processName: %s\n", tokenNode->tokenId, tokenNode->processName); + } + + TOKEN_QUEUE_NODE_INFO_SET(tmp, aplStr, processname, tokenId, exist, dcap, dacpNum); + ret = TokenInfoSave(&tmp); + if (ret == 0) { + return result; + } + atPoint->tokenId = tokenId; + atPoint->tokenAttr = 0; + return result; +} + +int SendString(const char *str, int fd) +{ + int writtenSize; + int len = strlen(str); + + writtenSize = write(fd, str, len); + if (len != writtenSize) { + ACCESSTOKEN_LOG_ERROR("SendString write failed."); + return ERR; + } + return SUCCESS; +} + +void WriteToFile(const cJSON *root) +{ + char *jsonStr; + jsonStr = cJSON_PrintUnformatted(root); + if (jsonStr == NULL) { + ACCESSTOKEN_LOG_ERROR("cJSON_PrintUnformatted failed."); + return; + } + ACCESSTOKEN_LOG_INFO("jsonStr %s.\n", jsonStr); + + do { + int fd = open(TOKEN_ID_CFG_PATH, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); + if (fd < 0) { + break; + } + int strLen = strlen(jsonStr); + int writtenLen = write(fd, (void *)jsonStr, strLen); + close(fd); + if (writtenLen != strLen) { + ACCESSTOKEN_LOG_ERROR("write failed."); + break; + } + } while (0); + + cJSON_free(jsonStr); + return; +} + +int ExistNewTokenInfo(const NativeTokenQueue *head) +{ + const NativeTokenQueue *iter = head; + while (iter != NULL) { + if (iter->flag == 0) { + return 1; + } + iter = iter->next; + } + return 0; +} +void SaveTokenIdToCfg(const NativeTokenQueue *head) +{ + const NativeTokenQueue *iter = head; + char *fileBuff; + cJSON *record; + int ret; + + ret = ExistNewTokenInfo(head); + if (ret == 0) { + ACCESSTOKEN_LOG_INFO("there is no new info.\n"); + return; + } + fileBuff = GetFileBuff(TOKEN_ID_CFG_PATH); + if (fileBuff == NULL) { + return; + } + + record = cJSON_Parse(fileBuff); + free(fileBuff); + fileBuff = NULL; + + if (record == NULL) { + ACCESSTOKEN_LOG_ERROR("cJSON_Parse failed."); + return; + } + + while (iter != NULL) { + if (iter->flag == 1) { + continue; + } + cJSON *node = cJSON_CreateObject(); + if (node == NULL) { + ACCESSTOKEN_LOG_ERROR("cJSON_CreateObject failed."); + cJSON_Delete(record); + return; + } + cJSON_AddItemToObject(node, "processName", cJSON_CreateString(iter->processName)); + cJSON_AddItemToObject(node, "tokenId", cJSON_CreateNumber(iter->tokenId)); + cJSON_AddItemToArray(record, node); + iter = iter->next; + } + WriteToFile(record); + cJSON_Delete(record); + return; +} + +char * GetStringToBeSync(NativeTokenQueue *head) +{ + if (head == NULL) { + return NULL; + } + + cJSON *array = cJSON_CreateArray(); + if (array == NULL) { + return NULL; + } + + NativeTokenQueue *curr = head; + while (curr != 0) { + cJSON *object = cJSON_CreateObject(); + if (object == NULL) { + cJSON_Delete(array); + return NULL; + } + cJSON_AddItemToObject(object, "processName", cJSON_CreateString(curr->processName)); + cJSON_AddItemToObject(object, "APL", cJSON_CreateNumber(curr->apl)); + cJSON_AddItemToObject(object, "version", cJSON_CreateNumber(DEFAULT_AT_VERSION)); + cJSON_AddItemToObject(object, "tokenId", cJSON_CreateNumber(curr->tokenId)); + cJSON_AddItemToObject(object, "tokenAttr", cJSON_CreateNumber(0)); + + cJSON *dcapsArr = cJSON_CreateArray(); + if (dcapsArr == NULL) { + cJSON_Delete(array); + return NULL; + } + for (int i = 0; i < curr->dcapsNum; i++) { + cJSON_AddItemToArray(dcapsArr, cJSON_CreateString(curr->dcaps[i])); + } + cJSON_AddItemToObject(object, "dcaps", dcapsArr); + cJSON_AddItemToArray(array, object); + + NativeTokenQueue *node; + node = curr; + curr = curr->next; + free(node); + node = NULL; + } + + cJSON *root = cJSON_CreateObject(); + if (root == NULL) { + cJSON_Delete(array); + return NULL; + } + + cJSON_AddItemToObject(root, TRANSFER_KEY_WORDS, array); + + char *jsonStr = cJSON_PrintUnformatted(root); + if (jsonStr == NULL) { + cJSON_Delete(root); + return NULL; + } + + char *str = (char *)malloc(sizeof(char) * (strlen(jsonStr) + 1)); + if (str == NULL) { + cJSON_free(jsonStr); + cJSON_Delete(root); + return NULL; + } + + (void)strcpy_s(str, strlen(jsonStr) + 1, jsonStr); + cJSON_free(jsonStr); + cJSON_Delete(root); + return str; +} + +int SyncToAtm(void) +{ + int result; + struct sockaddr_un addr; + int fd; + char *str; + + /* get data to be processed */ + pthread_mutex_lock(&g_tokenQueueHeadLock); + NativeTokenQueue *begin = g_tokenQueueHead->next; + g_tokenQueueHead->next = NULL; + pthread_mutex_unlock(&g_tokenQueueHeadLock); + + /* update the token file */ + SaveTokenIdToCfg(begin); + + str = GetStringToBeSync(begin); + if (str == NULL) { + return SUCCESS; + } + + /* set socket */ + fd = socket(AF_UNIX, SOCK_STREAM, 0); + (void)memset_s(&addr, sizeof(struct sockaddr_un), 0, sizeof(struct sockaddr_un)); + addr.sun_family = AF_UNIX; + if (memcpy_s(addr.sun_path, sizeof(addr.sun_path), SOCKET_FILE, sizeof(addr.sun_path) - 1) != EOK) { + ACCESSTOKEN_LOG_ERROR("memcpy_s failed."); + return ERR; + } + result = connect(fd, (struct sockaddr *)&addr, sizeof(addr)); // 建立socket后默认connect()函数为阻塞连接状态 + if (result != 0) { + ACCESSTOKEN_LOG_ERROR("connect failed %d.", result); + return ERR; + } + + result = SendString(str, fd); + free(str); + close(fd); + return result; +} + +void *ThreadTransferFunc(const void *args) +{ + uint64_t result; + + /* + getpram + */ + + g_signalFd = eventfd(0, 0); + if (g_signalFd == -1) { + ACCESSTOKEN_LOG_ERROR("eventfd failed."); + return NULL; + } + + g_isAtmExist = 1; + while (1) { + int ret; + ret = read(g_signalFd, &result, sizeof(uint64_t)); + if (ret == -1) { + ACCESSTOKEN_LOG_ERROR("read failed."); + continue; + } + ret = SyncToAtm(); + if (ret == -1) { + ACCESSTOKEN_LOG_ERROR("SyncToAtm failed."); + } + } + return NULL; +} diff --git a/interfaces/innerkits/atlib/test/BUILD.gn b/interfaces/innerkits/atlib/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..913506e798fe9602c0ad44eb394c9f0aba84f5f3 --- /dev/null +++ b/interfaces/innerkits/atlib/test/BUILD.gn @@ -0,0 +1,44 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +ohos_unittest("libaccesstoken_lib_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "//utils/native/base/include", + "//third_party/cJSON", + "//third_party/bounds_checking_function/include", + "//base/security/access_token/interfaces/innerkits/atlib/main/include" + ] + + sources = [ "unittest/cpp/src/accesstokenlib_kit_test.cpp" ] + cflags_cc = ["-fexceptions" ] + ldflags = ["-lpthread",] + deps = [ + "//third_party/cJSON:cjson_static", + "//utils/native/base:utils", + "//third_party/googletest:gmock", + "//third_party/googletest:gtest", + "//third_party/libuv:uv_static", + "//third_party/bounds_checking_function:libsec_static", + ] +} + +group("unittest") { + testonly = true + deps = [ ":libaccesstoken_lib_test" ] +} diff --git a/interfaces/innerkits/atlib/test/unittest/cpp/src/accesstokenlib_kit_test.cpp b/interfaces/innerkits/atlib/test/unittest/cpp/src/accesstokenlib_kit_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..04a1e5ffb90622d6c0452f0590e5c4810b45e816 --- /dev/null +++ b/interfaces/innerkits/atlib/test/unittest/cpp/src/accesstokenlib_kit_test.cpp @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstokenlib_kit_test.h" + +#include "accesstokenlib_kit.h" +#include "accesstoken_lib.h" + +using namespace testing::ext; +using namespace OHOS::Security; + +void TokenLibKitTest::SetUpTestCase() +{} + +void TokenLibKitTest::TearDownTestCase() +{} + +void TokenLibKitTest::SetUp() +{} + +void TokenLibKitTest::TearDown() +{} + +extern char *GetFileBuff(const char *cfg); + +void * ThreadATMFuncBackUp(void *args) +{ + socklen_t len = sizeof(struct sockaddr_un); + struct sockaddr_un addr; + struct sockaddr_un clientAddr; + int listenFd, ret; + int readLen; + + /* set socket */ + (void)memset_s(&addr, sizeof(addr), 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + if (memcpy_s(addr.sun_path, sizeof(addr.sun_path), SOCKET_FILE, sizeof(addr.sun_path) - 1) != EOK) { + return NULL; + } + unlink(SOCKET_FILE); + listenFd = socket(AF_UNIX, SOCK_STREAM, 0); + if (listenFd < 0) { + ACCESSTOKEN_LOG_INFO("socket failed %d\n", listenFd); + return NULL; + } + + ::bind(listenFd, (struct sockaddr *)(&addr), (unsigned int)len); + + ret = listen(listenFd, 1); + if (ret < 0) { + ACCESSTOKEN_LOG_INFO("listenFd failed %d\n", errno); + remove(SOCKET_FILE); + close(listenFd); + return NULL; + } + while (1) { + int sockFd = accept(listenFd, (struct sockaddr *)(&clientAddr), &len); + ACCESSTOKEN_LOG_INFO("accept sockFd %d\n", sockFd); + do { + readLen = read(sockFd, OHOS::Security::TokenLibKitTest::buffer, 102400); + OHOS::Security::TokenLibKitTest::buffer[readLen] = '\0'; + ACCESSTOKEN_LOG_INFO("read :%s\n", OHOS::Security::TokenLibKitTest::buffer); + } while (readLen > 0); + + close(sockFd); + if (readLen < 0) { + break; + } + } + close(listenFd); + return NULL; +} + +int Start(const char *processName) +{ + const char *processname = processName; + const char **dcaps = (const char **)malloc(sizeof(char *) * 2); + dcaps[0] = "AT_CAP"; + dcaps[1] = "ST_CAP"; + int dcapNum = 2; + pthread_t tid[2]; + (void)GetAccessTokenId(processname, dcaps, dcapNum, "system_core"); + + if (strcmp("foundation", processname) == 0) { + (void)pthread_create(&tid[0], 0, ThreadTransferFunc, NULL); + } + return 0; +} + +HWTEST_F(TokenLibKitTest, TestAtlib, TestSize.Level1) +{ + pthread_t tid[2]; + + AtlibInit(); + (void)pthread_create(&tid[1], 0, ThreadATMFuncBackUp, NULL); + sleep(5); + Start("process1"); + Start("process2"); + Start("process3"); + Start("process4"); + sleep(5); + Start("foundation"); + Start("process5"); + Start("process6"); + sleep(20); + Start("process7"); + Start("process8"); + Start("process9"); + sleep(50); + +} diff --git a/interfaces/innerkits/atlib/test/unittest/cpp/src/accesstokenlib_kit_test.h b/interfaces/innerkits/atlib/test/unittest/cpp/src/accesstokenlib_kit_test.h new file mode 100644 index 0000000000000000000000000000000000000000..f03660d8ce29bf1a927c1da060fdfedbb9bdd99b --- /dev/null +++ b/interfaces/innerkits/atlib/test/unittest/cpp/src/accesstokenlib_kit_test.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKENSYNC_KIT_TEST_H +#define TOKENSYNC_KIT_TEST_H + +#include + +namespace OHOS { +namespace Security { +class TokenLibKitTest : public testing::Test { +public: + static char buffer[102400]; + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace Security +} // namespace OHOS +#endif // TOKENSYNC_KIT_TEST_H diff --git a/interfaces/innerkits/tokensync/BUILD.gn b/interfaces/innerkits/tokensync/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0fe7a79073e3f5b663afec7443584d4398f8846a --- /dev/null +++ b/interfaces/innerkits/tokensync/BUILD.gn @@ -0,0 +1,64 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +################################################################ +# C++, Main, source file here. +################################################################ +config("tokensync") { + visibility = [ ":*" ] + include_dirs = [ "main/cpp/include" ] +} + +ohos_shared_library("libtokensync_sdk") { + subsystem_name = "security" + part_name = "access_token" + + output_name = "libtokensync_sdk" + + public_configs = [ ":tokensync" ] + + include_dirs = [ + "//utils/native/base/include", + "main/cpp/include", + "main/cpp/src", + "//base/security/access_token/frameworks/tokensync/include", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/interfaces/innerkits/tokensync/main/cpp/include" + #"//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include/permission", + ] + + sources = [ + #"main/cpp/src/permission/permission_kit.cpp", + #"main/cpp/src/permission/permission_manager_client.cpp", + #"main/cpp/src/permission/permission_manager_proxy.cpp", + "main/cpp/src/tokensync_kit.cpp", + "main/cpp/src/tokensync_manager_client.cpp", + "main/cpp/src/tokensync_manager_proxy.cpp", + ] + + deps = [ + #"//base/security/permission/frameworks/permission_standard/permissioncommunicationadapter:permission_standard_communication_adapter_cxx", + #"//base/security/permission/frameworks/permission_standard/permissioninfrastructure:permission_standard_infrastructure_cxx", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] +} diff --git a/interfaces/innerkits/tokensync/main/cpp/include/tokensync_kit.h b/interfaces/innerkits/tokensync/main/cpp/include/tokensync_kit.h new file mode 100644 index 0000000000000000000000000000000000000000..c39e1a64a3c851b8ecb1578d6370f09d38a6e2ee --- /dev/null +++ b/interfaces/innerkits/tokensync/main/cpp/include/tokensync_kit.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_TOKENSYNC_KIT_H +#define INTERFACES_INNER_KITS_TOKENSYNC_KIT_H + +#include +#include + +namespace OHOS { +namespace Security { +namespace TokenSync { +class TokenSyncKit { +public: + static int VerifyPermission(const std::string& bundleName, const std::string& permissionName, int userId); +}; +} // namespace TokenSync +} // namespace Security +} // namespace OHOS + +#endif diff --git a/interfaces/innerkits/tokensync/main/cpp/src/tokensync_kit.cpp b/interfaces/innerkits/tokensync/main/cpp/src/tokensync_kit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..02a462ffbde3596de9630ae05290d0121afc39fc --- /dev/null +++ b/interfaces/innerkits/tokensync/main/cpp/src/tokensync_kit.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "tokensync_kit.h" + +#include +#include + +#include "accesstoken_log.h" +#include "tokensync_manager_client.h" + +namespace OHOS { +namespace Security { +namespace TokenSync { +using namespace std; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncKit"}; +} // namespace + +int TokenSyncKit::VerifyPermission(const string& bundleName, const string& permissionName, int userId) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "bundleName=%{public}s, permissionName=%{public}s, userId=%{public}d", + bundleName.c_str(), permissionName.c_str(), userId); + return TokenSyncManagerClient::GetInstance().VerifyPermission(bundleName, permissionName, userId); +} +} // namespace TokenSync +} // namespace Security +} // namespace OHOS diff --git a/interfaces/innerkits/tokensync/main/cpp/src/tokensync_manager_client.cpp b/interfaces/innerkits/tokensync/main/cpp/src/tokensync_manager_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..98f658bc65ba87727d2295767cd187b9fcf6a18f --- /dev/null +++ b/interfaces/innerkits/tokensync/main/cpp/src/tokensync_manager_client.cpp @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "tokensync_manager_client.h" + +#include "accesstoken_log.h" + +#include "iservice_registry.h" + +namespace OHOS { +namespace Security { +namespace TokenSync { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncManagerClient"}; +} // namespace + +TokenSyncManagerClient& TokenSyncManagerClient::GetInstance() +{ + static TokenSyncManagerClient instance; + return instance; +} + +TokenSyncManagerClient::TokenSyncManagerClient() +{} + +TokenSyncManagerClient::~TokenSyncManagerClient() +{} + +int TokenSyncManagerClient::VerifyPermission( + const std::string& bundleName, const std::string& permissionName, int userId) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return -1; + } + return proxy->VerifyPermission(bundleName, permissionName, userId); +} + +sptr TokenSyncManagerClient::GetProxy() const +{ + auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sam == nullptr) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: GetSystemAbilityManager is null", __func__); + return nullptr; + } + auto tokensyncSa = sam->GetSystemAbility(ITokenSyncManager::SA_ID_TOKENSYNC_MANAGER_SERVICE); + if (tokensyncSa == nullptr) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: GetSystemAbility %{public}d is null", __func__, + ITokenSyncManager::SA_ID_TOKENSYNC_MANAGER_SERVICE); + return nullptr; + } + + auto proxy = iface_cast(tokensyncSa); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: iface_cast get null", __func__); + return nullptr; + } + return proxy; +} +} // namespace TokenSync +} // namespace Security +} // namespace OHOS diff --git a/interfaces/innerkits/tokensync/main/cpp/src/tokensync_manager_client.h b/interfaces/innerkits/tokensync/main/cpp/src/tokensync_manager_client.h new file mode 100644 index 0000000000000000000000000000000000000000..06445abc50dc4f61445662636a85869843cf7526 --- /dev/null +++ b/interfaces/innerkits/tokensync/main/cpp/src/tokensync_manager_client.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_MANAGER_CLIENT_H +#define ACCESSTOKEN_MANAGER_CLIENT_H + +#include + +#include "i_tokensync_manager.h" + +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace TokenSync { +class TokenSyncManagerClient final { +public: + static TokenSyncManagerClient& GetInstance(); + + virtual ~TokenSyncManagerClient(); + + int VerifyPermission(const std::string& bundleName, const std::string& permissionName, int userId) const; + +private: + TokenSyncManagerClient(); + + DISALLOW_COPY_AND_MOVE(TokenSyncManagerClient); + + sptr GetProxy() const; +}; +} // namespace TokenSync +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_MANAGER_CLIENT_H diff --git a/interfaces/innerkits/tokensync/main/cpp/src/tokensync_manager_proxy.cpp b/interfaces/innerkits/tokensync/main/cpp/src/tokensync_manager_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a0e9f8300a65ce071b368392d6dafd11ccee321 --- /dev/null +++ b/interfaces/innerkits/tokensync/main/cpp/src/tokensync_manager_proxy.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "tokensync_manager_proxy.h" + +#include "accesstoken_log.h" + +#include "parcel.h" +#include "string_ex.h" + +namespace OHOS { +namespace Security { +namespace TokenSync { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncManagerProxy"}; +} + +TokenSyncManagerProxy::TokenSyncManagerProxy(const sptr& impl) : IRemoteProxy(impl) +{} + +TokenSyncManagerProxy::~TokenSyncManagerProxy() +{} + +int TokenSyncManagerProxy::VerifyPermission( + const std::string& bundleName, const std::string& permissionName, int userId) +{ + MessageParcel data; + data.WriteInterfaceToken(ITokenSyncManager::GetDescriptor()); + if (!data.WriteString(bundleName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write bundleName", __func__); + return -1; + } + if (!data.WriteString(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__); + return -1; + } + if (!data.WriteInt32(userId)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write userId", __func__); + return -1; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return -1; + } + int32_t requestResult = remote->SendRequest( + static_cast(ITokenSyncManager::InterfaceCode::VERIFY_PERMISSION), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return -1; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + return result; +} +} // namespace TokenSync +} // namespace Security +} // namespace OHOS diff --git a/interfaces/innerkits/tokensync/main/cpp/src/tokensync_manager_proxy.h b/interfaces/innerkits/tokensync/main/cpp/src/tokensync_manager_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..fc0dbc10d1b18c5fe31336bfac4d8916f06c88f1 --- /dev/null +++ b/interfaces/innerkits/tokensync/main/cpp/src/tokensync_manager_proxy.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKENSYNC_MANAGER_PROXY_H +#define TOKENSYNC_MANAGER_PROXY_H + +#include + +#include "i_tokensync_manager.h" +#include "iremote_broker.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace Security { +namespace TokenSync { +class TokenSyncManagerProxy : public IRemoteProxy { +public: + explicit TokenSyncManagerProxy(const sptr& impl); + virtual ~TokenSyncManagerProxy() override; + + int VerifyPermission(const std::string& packageName, const std::string& permissionName, int userId) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace TokenSync +} // namespace Security +} // namespace OHOS +#endif // TOKENSYNC_MANAGER_PROXY_H diff --git a/interfaces/innerkits/tokensync/test/BUILD.gn b/interfaces/innerkits/tokensync/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..afbd3655fe10526155461090e03a6562d935f9f8 --- /dev/null +++ b/interfaces/innerkits/tokensync/test/BUILD.gn @@ -0,0 +1,42 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +ohos_unittest("libtokensync_sdk_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "//utils/native/base/include", + "//third_party/googletest/include", + #"//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include/permission/", + "//base/security/access_token/interfaces/innerkits/tokensync/main/cpp/include" + ] + + sources = [ "unittest/cpp/src/tokensync_kit_test.cpp" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ +#"//base/security/permission/frameworks/permission_standard/permissioninfrastructure:permission_standard_infrastructure_cxx", + "//base/security/access_token/interfaces/innerkits/tokensync:libtokensync_sdk", + "//utils/native/base:utils", + ] +} + +group("unittest") { + testonly = true + deps = [ ":libtokensync_sdk_test" ] +} diff --git a/interfaces/innerkits/tokensync/test/unittest/cpp/src/tokensync_kit_test.cpp b/interfaces/innerkits/tokensync/test/unittest/cpp/src/tokensync_kit_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b4ae1174ee9f70c5f8be33585ce4c767d025674a --- /dev/null +++ b/interfaces/innerkits/tokensync/test/unittest/cpp/src/tokensync_kit_test.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "tokensync_kit_test.h" + +#include "tokensync_kit.h" + +using namespace testing::ext; +using namespace OHOS::Security::TokenSync; + +void TokenSyncKitTest::SetUpTestCase() +{} + +void TokenSyncKitTest::TearDownTestCase() +{ +} + +void TokenSyncKitTest::SetUp() +{ +} + +void TokenSyncKitTest::TearDown() +{} + +/** + * @tc.name: VerifyPermission001 + * @tc.desc: Verify user granted permission + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(TokenSyncKitTest, VerifyPermission001, TestSize.Level1) +{ + const std::string TEST_BUNDLE_NAME = "ohos"; + const std::string TEST_PERMISSION_NAME_ALPHA = "ohos.permission.ALPHA"; + const int TEST_USER_ID = 0; + int ret = TokenSyncKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA, TEST_USER_ID); + + ASSERT_EQ(0, ret); +} + diff --git a/interfaces/innerkits/tokensync/test/unittest/cpp/src/tokensync_kit_test.h b/interfaces/innerkits/tokensync/test/unittest/cpp/src/tokensync_kit_test.h new file mode 100644 index 0000000000000000000000000000000000000000..4202bcd9bc86741fa1629371ec1fe59a6e6a1455 --- /dev/null +++ b/interfaces/innerkits/tokensync/test/unittest/cpp/src/tokensync_kit_test.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKENSYNC_KIT_TEST_H +#define TOKENSYNC_KIT_TEST_H + +#include + +namespace OHOS { +namespace Security { +namespace TokenSync { +class TokenSyncKitTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace TokenSync +} // namespace Security +} // namespace OHOS +#endif // TOKENSYNC_KIT_TEST_H diff --git a/ohos.build b/ohos.build index f8bc9d11fc3b32f44714844cd5f9e93365e2372e..f87ae64db91df4d037205238260e02cdf985e38d 100644 --- a/ohos.build +++ b/ohos.build @@ -11,7 +11,6 @@ "name": "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", "header": { "header_files": [ - "accesstoken.h", "accesstoken_kit.h" ], "header_base": "//base/security/access_token/interfaces/innerkits/accesstoken/main/cpp/include" @@ -19,10 +18,12 @@ } ], "module_list": [ - "//base/security/access_token:accesstoken_build_module_standard" + "//base/security/access_token:accesstoken_build_module", + "//base/security/access_token:tokensync_build_module" ], "test_list": [ - "//base/security/access_token:accesstoken_build_module_standard_test" + "//base/security/access_token:accesstoken_build_module_test", + "//base/security/access_token/interfaces/innerkits/accesstoken/test:unittest" ] } } diff --git a/services/accesstokenmanager/BUILD.gn b/services/accesstokenmanager/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4622a3086d424227e49d9ced179cd855fbd27fae --- /dev/null +++ b/services/accesstokenmanager/BUILD.gn @@ -0,0 +1,78 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + + +ohos_prebuilt_etc("access_token.rc") { + source = "access_token.cfg" + relative_install_dir = "init" + subsystem_name = "security" + part_name = "access_token" +} + +ohos_shared_library("accesstoken_manager_service") { + subsystem_name = "security" + part_name = "access_token" + + include_dirs = [ + "main/cpp/include/service", + "main/cpp/include/token", + "main/cpp/include/permission", + "main/cpp/include/database", + "//utils/system/safwk/native/include", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/frameworks/accesstoken/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/main/cpp/include", + "//third_party/json/include", + ] + + sources = [ + "main/cpp/src/service/accesstoken_manager_service.cpp", + "main/cpp/src/service/accesstoken_manager_stub.cpp", + "main/cpp/src/token/accesstoken_id_manager.cpp", + "main/cpp/src/token/accesstoken_info_manager.cpp", + "main/cpp/src/token/hap_token_info_inner.cpp", + "main/cpp/src/token/native_token_info_inner.cpp", + "main/cpp/src/permission/permission_manager.cpp", + "main/cpp/src/permission/permission_definition_cache.cpp", + "main/cpp/src/permission/permission_policy_set.cpp", + "main/cpp/src/permission/permission_validator.cpp", + "main/cpp/src/database/data_storage.cpp", + "main/cpp/src/database/data_translator.cpp", + "main/cpp/src/database/generic_values.cpp", + "main/cpp/src/database/sqlite_helper.cpp", + "main/cpp/src/database/sqlite_storage.cpp", + "main/cpp/src/database/statement.cpp", + "main/cpp/src/database/variant_value.cpp", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + #"//base/security/accesstoken/frameworks/accesstooken/permissioncommunicationadapter:permission_standard_communication_adapter_cxx", + #"//base/security/accesstoken/frameworks/accesstooken/common:permission_standard_infrastructure_cxx", + "//third_party/sqlite:sqlite", + "//base/security/access_token/frameworks/common:accesstoken_common_cxx", + "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", + "//base/security/access_token/services/accesstokenmanager:access_token.rc", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] +} diff --git a/services/accesstokenmanager/access_token.cfg b/services/accesstokenmanager/access_token.cfg new file mode 100644 index 0000000000000000000000000000000000000000..e06136d1c671f2e6d420ae1107314fc0e29938cf --- /dev/null +++ b/services/accesstokenmanager/access_token.cfg @@ -0,0 +1,17 @@ +{ + "jobs" : [{ + "name" : "late-fs", + "cmds" : [ + "start accesstoken_service" + ] + } + ], + "services" : [{ + "name" : "accesstoken_service", + "path" : ["/system/bin/sa_main", "/system/profile/accesstoken_service.xml"], + "importance" : -20, + "uid" : "system", + "gid" : ["system"] + } + ] +} diff --git a/services/accesstokenmanager/access_token.rc b/services/accesstokenmanager/access_token.rc new file mode 100644 index 0000000000000000000000000000000000000000..68b9f548b6f5f31b3fc30abc1da6be5c14c380d4 --- /dev/null +++ b/services/accesstokenmanager/access_token.rc @@ -0,0 +1,22 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +on late-fs + start accesstoken_service + +service accesstoken_service /system/bin/sa_main /system/profile/accesstoken_service.xml + class accesstoken_service + priority -20 + user system + group system + seclabel u:r:accesstoken_service:s0 diff --git a/services/accesstokenmanager/main/cpp/include/database/data_storage.h b/services/accesstokenmanager/main/cpp/include/database/data_storage.h new file mode 100644 index 0000000000000000000000000000000000000000..9233596bbb9931ea52eb3fb95d6d6a7f5a9bf01a --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/database/data_storage.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATA_STORAGE_H +#define DATA_STORAGE_H + +#include +#include + +#include "generic_values.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class DataStorage { +public: + enum DataType { + ACCESSTOKEN_HAP_INFO, + ACCESSTOKEN_NATIVE_INFO, + ACCESSTOKEN_PERMISSION_DEF, + ACCESSTOKEN_PERMISSION_STATE, + }; + + static DataStorage& GetRealDataStorage(); + + virtual ~DataStorage() = default; + + virtual int Add(const DataType type, const std::vector& values) = 0; + + virtual int Remove(const DataType type, const GenericValues& conditions) = 0; + + virtual int Modify(const DataType type, const GenericValues& modifyValues, const GenericValues& conditions) = 0; + + virtual int Find(const DataType type, std::vector& results) = 0; + + virtual int RefreshAll(const DataType type, const std::vector& values) = 0; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // DATA_STORAGE_H diff --git a/services/accesstokenmanager/main/cpp/include/database/data_translator.h b/services/accesstokenmanager/main/cpp/include/database/data_translator.h new file mode 100644 index 0000000000000000000000000000000000000000..1be472818eab2de3bcd06bb96afd0ecceabfcb71 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/database/data_translator.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATA_TRANSLATOR_H +#define DATA_TRANSLATOR_H + +#include + +#include "hap_token_info_inner.h" +#include "native_token_info_inner.h" +#include "generic_values.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class DataTranslator final { +public: + static int TranslationIntoGenericValues(const PermissionDef& inPermissionDef, GenericValues& outGenericValues); + static int TranslationIntoPermissionDef(const GenericValues& inGenericValues, PermissionDef& outPermissionDef); + static int TranslationIntoGenericValues(const PermissionStateFull& inPermissionState, + const unsigned int grantIndex, GenericValues& outGenericValues); + static int TranslationIntoPermissionStateFull(const GenericValues& inGenericValues, + PermissionStateFull& outPermissionState); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // DATA_TRANSLATOR_H diff --git a/services/accesstokenmanager/main/cpp/include/database/field_const.h b/services/accesstokenmanager/main/cpp/include/database/field_const.h new file mode 100644 index 0000000000000000000000000000000000000000..3d9ec533f0af94d8ccb66757bf87655eabe224a8 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/database/field_const.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIELD_CONST_H +#define FIELD_CONST_H + +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +const std::string FIELD_TOKEN_ID = "token_id"; +const std::string FIELD_USER_ID = "user_id"; +const std::string FIELD_BUNDLE_NAME = "bundle_name"; +const std::string FIELD_INST_INDEX = "inst_index"; +const std::string FIELD_APP_ID = "app_id"; +const std::string FIELD_DEVICE_ID = "device_id"; +const std::string FIELD_APL = "apl"; +const std::string FIELD_TOKEN_VERSION = "token_version"; +const std::string FIELD_TOKEN_ATTR = "token_attr"; +const std::string FIELD_PROCESS_NAME = "process_name"; +const std::string FIELD_DCAP = "dcap"; +const std::string FIELD_PERMISSION_NAME = "permission_name"; +const std::string FIELD_GRANT_MODE = "grant_mode"; +const std::string FIELD_AVAILABLE_SCOPE = "available_scope"; +const std::string FIELD_LABEL = "label"; +const std::string FIELD_LABEL_ID = "label_id"; +const std::string FIELD_DESCRIPTION = "description"; +const std::string FIELD_DESCRIPTION_ID = "description_id"; +const std::string FIELD_GRANT_STATE = "grant_state"; +const std::string FIELD_GRANT_FLAG = "grant_flag"; +const std::string FIELD_GRANT_IS_GENERAL = "is_general"; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // FIELD_CONST_H diff --git a/services/accesstokenmanager/main/cpp/include/database/generic_values.h b/services/accesstokenmanager/main/cpp/include/database/generic_values.h new file mode 100644 index 0000000000000000000000000000000000000000..55c6b7ba64fb1636c2585dde5000811bb9120ed8 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/database/generic_values.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GENERIC_VALUES_H +#define GENERIC_VALUES_H + +#include +#include +#include + +#include "variant_value.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class GenericValues final { +public: + GenericValues() = default; + virtual ~GenericValues() = default; + + void Put(const std::string& key, int value); + + void Put(const std::string& key, const std::string& value); + + void Put(const std::string& key, const VariantValue& value); + + std::vector GetAllKeys() const; + + VariantValue Get(const std::string& key) const; + + int GetInt(const std::string& key) const; + + std::string GetString(const std::string& key) const; + +private: + std::map map_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // GENERIC_VALUES_H diff --git a/services/accesstokenmanager/main/cpp/include/database/sqlite_helper.h b/services/accesstokenmanager/main/cpp/include/database/sqlite_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..003859839211d37a85d318c30ef86e0b148ebe9a --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/database/sqlite_helper.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SQLITE_HELPER_H +#define SQLITE_HELPER_H + +#include + +#include "statement.h" + +#include "sqlite3sym.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class SqliteHelper { +public: + explicit SqliteHelper(const std::string& dbName, const std::string& dbPath, int version); + virtual ~SqliteHelper(); + + void Open(); + void Close(); + + int BeginTransaction() const; + int CommitTransaction() const; + int RollbackTransaction() const; + + Statement Prepare(const std::string& sql) const; + int ExecuteSql(const std::string& sql) const; + std::string SpitError() const; + + virtual void OnCreate() = 0; + virtual void OnUpdate() = 0; + +private: + inline static const std::string PRAGMA_VERSION_COMMAND = "PRAGMA user_version"; + static const int GENERAL_ERROR = -1; + + const std::string dbName_; + const std::string dbPath_; + int currentVersion_; + sqlite3* db_; + + int GetVersion() const; + void SetVersion() const; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // SQLITE_HELPER_H diff --git a/services/accesstokenmanager/main/cpp/include/database/sqlite_storage.h b/services/accesstokenmanager/main/cpp/include/database/sqlite_storage.h new file mode 100644 index 0000000000000000000000000000000000000000..5aeb7871341fbd0d0d4f0762a3ca69704a9d2885 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/database/sqlite_storage.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SQLITE_STORAGE_H +#define SQLITE_STORAGE_H + +#include "data_storage.h" +#include "sqlite_helper.h" +#include "field_const.h" + +#include "nocopyable.h" +#include "rwlock.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class SqliteStorage : public DataStorage, public SqliteHelper { +public: + enum ExecuteResult { FAILURE = -1, SUCCESS }; + + struct SqliteTable { + public: + std::string tableName_; + std::vector tableColumnNames_; + }; + + static SqliteStorage& GetInstance(); + + ~SqliteStorage() override; + + int Add(const DataType type, const std::vector& values) override; + + int Remove(const DataType type, const GenericValues& conditions) override; + + int Modify(const DataType type, const GenericValues& modifyValues, const GenericValues& conditions) override; + + int Find(const DataType type, std::vector& results) override; + + int RefreshAll(const DataType type, const std::vector& values) override; + + void OnCreate() override; + void OnUpdate() override; + +private: + SqliteStorage(); + DISALLOW_COPY_AND_MOVE(SqliteStorage); + + std::map dataTypeToSqlTable_; + OHOS::Utils::RWLock rwLock_; + + int CreateHapTokenInfoTable() const; + int CreateNativeTokenInfoTable() const; + int CreatePermissionDefinitionTable() const; + int CreatePermissionStateTable() const; + + std::string CreateInsertPrepareSqlCmd(const DataType type) const; + std::string CreateDeletePrepareSqlCmd( + const DataType type, const std::vector& columnNames = std::vector()) const; + std::string CreateUpdatePrepareSqlCmd(const DataType type, const std::vector& modifyColumns, + const std::vector& conditionColumns) const; + std::string CreateSelectPrepareSqlCmd(const DataType type) const; + +private: + inline static const std::string HAP_TOKEN_INFO_TABLE = "hap_token_info_table"; + inline static const std::string NATIVE_TOKEN_INFO_TABLE = "native_token_info_table"; + inline static const std::string PERMISSION_DEF_TABLE = "permission_definition_table"; + inline static const std::string PERMISSION_STATE_TABLE = "permission_state_table"; + inline static const std::string DATABASE_NAME = "access_token.db"; + inline static const std::string DATABASE_PATH = "/data/system/"; + static const int DATABASE_VERSION = 1; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // SQLITE_STORAGE_H diff --git a/services/accesstokenmanager/main/cpp/include/database/statement.h b/services/accesstokenmanager/main/cpp/include/database/statement.h new file mode 100644 index 0000000000000000000000000000000000000000..e84ec0b2fe71f814c82843855dbd9703d4626127 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/database/statement.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef STATEMENT_H +#define STATEMENT_H + +#include + +#include "variant_value.h" + +#include "sqlite3sym.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class Statement final { +public: + enum State { BUSY, ROW, DONE, MISUSE, UNKNOWN }; + + Statement(sqlite3* db, const std::string& sql); + virtual ~Statement(); + + void Bind(const int index, const std::string& text); + void Bind(const int index, int value); + void Bind(const std::string& tableColumnName, const VariantValue& value); + + State Step(); + int Reset(); + + std::string GetColumnString(const int column) const; + int GetColumnInt(const int column) const; + std::string GetColumnName(const int column) const; + int GetParameterIndex(const std::string& name) const; + int GetColumnCount() const; + VariantValue GetValue(const int column) const; + +private: + sqlite3* db_; + sqlite3_stmt* statement_; + const std::string sql_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // STATEMENT_H diff --git a/services/accesstokenmanager/main/cpp/include/database/variant_value.h b/services/accesstokenmanager/main/cpp/include/database/variant_value.h new file mode 100644 index 0000000000000000000000000000000000000000..cfb16f8e1648b814d8bf923d7582c5a36a5294b9 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/database/variant_value.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef VARIANT_VALUE_H +#define VARIANT_VALUE_H + +#include +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +enum class ValueType { + TYPE_NULL, + TYPE_INT, + TYPE_STRING, +}; + +class VariantValue final { +public: + VariantValue(); + virtual ~VariantValue(); + + explicit VariantValue(int value); + explicit VariantValue(const std::string& value); + + ValueType GetType() const; + int GetInt() const; + std::string GetString() const; + + static const int DEFAULT_VALUE = -1; + +private: + ValueType type_; + std::variant value_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // VARIANT_VALUE_H diff --git a/services/accesstokenmanager/main/cpp/include/permission/permission_definition_cache.h b/services/accesstokenmanager/main/cpp/include/permission/permission_definition_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..76e492897fac0c2b023a75626e0446a6962211f8 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/permission/permission_definition_cache.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_DEFINITION_CACHE_H +#define PERMISSION_DEFINITION_CACHE_H + +#include +#include + +#include "permission_def.h" + +#include "rwlock.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionDefinitionCache final { +public: + static PermissionDefinitionCache& GetInstance(); + + virtual ~PermissionDefinitionCache(); + + bool Insert(const PermissionDef& info); + + void DeleteByBundleName(const std::string& bundleName); + + int FindByPermissionName(const std::string& permissionName, PermissionDef& info); + + bool IsSystemGrantedPermission(const std::string& permissionName); + + bool IsUserGrantedPermission(const std::string& permissionName); + + bool HasDefinition(const std::string& permissionName); + +private: + PermissionDefinitionCache(); + + bool IsGrantedModeEqualInner(const std::string& permissionName, int grantMode) const; + + DISALLOW_COPY_AND_MOVE(PermissionDefinitionCache); + + /** + * key: the permission name. + * value: the object of PermissionDef. + */ + std::map permissionDefinitionMap_; + + OHOS::Utils::RWLock cacheLock_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_DEFINITION_CACHE_H diff --git a/services/accesstokenmanager/main/cpp/include/permission/permission_manager.h b/services/accesstokenmanager/main/cpp/include/permission/permission_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..5925deec7907f15420c4a6499702f9e490f6a46a --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/permission/permission_manager.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_MANAGER_H +#define PERMISSION_MANAGER_H + +#include +#include + +#include "access_token.h" +#include "hap_token_info_inner.h" +#include "permission_def.h" +#include "permission_state_full.h" + +#include "rwlock.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +static const int DEFAULT_PERMISSION_FLAGS = 0; +class PermissionManager final { +public: + static PermissionManager& GetInstance(); + virtual ~PermissionManager(); + + void AddDefPermissions(const std::vector& permList); + void RemoveDefPermissions(AccessTokenID tokenID); + int VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName); + int GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult); + int GetDefPermissions(AccessTokenID tokenID, std::vector& permList); + int GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant); + int GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName); + void GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag); + void RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag); + void ClearUserGrantedPermissionState(AccessTokenID tokenID); +private: + PermissionManager(); + int UpdatePermissionStatus(PermissionStateFull& permStat, bool isGranted, int flag); + void UpdateTokenPermissionState( + AccessTokenID tokenID, const std::string& permissionName, bool isGranted, int flag); + + int QueryPermissionFlag(const PermissionStateFull& permStat); + int QueryPermissionStatus(const PermissionStateFull& permStat); + std::string TransferPermissionDefToString(const PermissionDef& inPermissionDef); + bool IsPermissionFlagValid(int flag) const; + bool IsGrantModeValid(const int grantMode) const; + bool IsAvailableScopeValid(const int availableScope) const; + bool IsPermissionDefValid(const PermissionDef& permissionDef) const; + + DISALLOW_COPY_AND_MOVE(PermissionManager); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_MANAGER_H diff --git a/services/accesstokenmanager/main/cpp/include/permission/permission_policy_set.h b/services/accesstokenmanager/main/cpp/include/permission/permission_policy_set.h new file mode 100644 index 0000000000000000000000000000000000000000..b51fe07132ad4a52be5925cf2fb6fa4c01d1c780 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/permission/permission_policy_set.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_POLICY_SET_H +#define PERMISSION_POLICY_SET_H + +#include "permission_def.h" +#include "permission_state_full.h" +#include "access_token.h" +#include "generic_values.h" + +#include +#include +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PermissionPolicySet final { +public: + PermissionPolicySet() : tokenId_(0) {}; + virtual ~PermissionPolicySet() {}; + + static std::shared_ptr BuildPermissionPolicySet(AccessTokenID tokenId, + const std::vector& permList, const std::vector& permStateList); + static std::shared_ptr RestorePermissionPolicy(AccessTokenID tokenId, + const std::vector& permDefRes, const std::vector& permStateRes); + void StorePermissionPolicySet(std::vector& permDefValueList, + std::vector& permStateValueList) const; + void Update(const std::vector& permList, const std::vector& permStateList); + void ToString(std::string& info) const; + std::vector permList_; + std::vector permStateList_; + +private: + static void MergePermissionStateFull(std::vector& permStateList, + const PermissionStateFull& state); + void UpdatePermStateFull(PermissionStateFull& permOld, const PermissionStateFull& permNew); + void UpdatePermDef(PermissionDef& permOld, const PermissionDef& permNew); + void StorePermissionDef(std::vector& valueList) const; + void StorePermissionState(std::vector& valueList) const; + void PermDefToString(const PermissionDef& def, std::string& info) const; + void PermStateFullToString(const PermissionStateFull& state, std::string& info) const; + AccessTokenID tokenId_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_POLICY_SET_H + diff --git a/services/accesstokenmanager/main/cpp/include/permission/permission_validator.h b/services/accesstokenmanager/main/cpp/include/permission/permission_validator.h new file mode 100644 index 0000000000000000000000000000000000000000..ebfb0b73b23230706a5bc122c47164043dd83f77 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/permission/permission_validator.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_VALIDATOR_H +#define PERMISSION_VALIDATOR_H +#include "permission_def.h" +#include "permission_state_full.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PermissionValidator final { +public: + PermissionValidator() {}; + ~PermissionValidator() {}; + + static bool IsPermissionNameValid(const std::string& permissionName); + static bool IsPermissionFlagValid(int flag); + static bool IsPermissionDefValid(const PermissionDef& permDef); + static bool IsPermissionStateValid(const PermissionStateFull& permState); + static void FilterInvalidPermisionDef( + const std::vector& permList, std::vector& result); + static void FilterInvalidPermisionState( + const std::vector& permList, std::vector& result); + static bool IsGrantModeValid(int grantMode); + static bool IsAvailableScopeValid(int availableScope); + static bool IsGrantStatusValid(int grantStaus); +private: + static void DeduplicateResDevID(const PermissionStateFull& permState, PermissionStateFull& result); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_VALIDATOR_H + diff --git a/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h new file mode 100644 index 0000000000000000000000000000000000000000..401437f4089849dc8b70e0160797315b26720c45 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_MANAGER_SERVICE_H +#define ACCESSTOKEN_MANAGER_SERVICE_H + +#include +#include + +#include "accesstoken_manager_stub.h" +#include "iremote_object.h" +#include "nocopyable.h" +#include "singleton.h" +#include "system_ability.h" +#include "hap_token_info.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; +class AccessTokenManagerService final : public SystemAbility, public AccessTokenManagerStub { + DECLARE_DELAYED_SINGLETON(AccessTokenManagerService); + DECLEAR_SYSTEM_ABILITY(AccessTokenManagerService); + +public: + void OnStart() override; + void OnStop() override; + + AccessTokenIDEx AllocHapToken(const HapInfoParcel& info, const HapPolicyParcel& policy) override; + int VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) override; + int GetDefPermission(const std::string& permissionName, PermissionDefParcel& permissionDefResult) override; + int GetDefPermissions(AccessTokenID tokenID, std::vector& permList) override; + int GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) override; + int GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) override; + int GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) override; + int RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) override; + int ClearUserGrantedPermissionState(AccessTokenID tokenID) override; + int DeleteToken(AccessTokenID tokenID) override; + int GetTokenType(AccessTokenID tokenID) override; + int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) override; + AccessTokenID GetHapTokenID(int userID, const std::string& bundleName, int instIndex) override; + AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID) override; + int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfoParcel& InfoParcel) override; + int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfoParcel& InfoParcel) override; + int UpdateHapToken(AccessTokenID tokenID, + const std::string& appIDDesc, const HapPolicyParcel& policyParcel) override; + +private: + bool Initialize() const; + + ServiceRunningState state_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_MANAGER_SERVICE_H diff --git a/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..f01b0edec5f77d5902be3b8f82d9d907690c689d --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_MANAGER_STUB_H +#define ACCESSTOKEN_MANAGER_STUB_H + +#include "i_accesstoken_manager.h" + +#include + +#include "iremote_stub.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class AccessTokenManagerStub : public IRemoteStub { +public: + AccessTokenManagerStub(); + virtual ~AccessTokenManagerStub(); + + int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& options) override; + +private: + void VerifyAccessTokenInner(MessageParcel& data, MessageParcel& reply); + void GetDefPermissionInner(MessageParcel& data, MessageParcel& reply); + void GetDefPermissionsInner(MessageParcel& data, MessageParcel& reply); + void GetReqPermissionsInner(MessageParcel& data, MessageParcel& reply); + void GetPermissionFlagInner(MessageParcel& data, MessageParcel& reply); + void GrantPermissionInner(MessageParcel& data, MessageParcel& reply); + void RevokePermissionInner(MessageParcel& data, MessageParcel& reply); + void ClearUserGrantedPermissionStateInner(MessageParcel& data, MessageParcel& reply); + void AllocHapTokenInner(MessageParcel& data, MessageParcel& reply); + void DeleteTokenInfoInner(MessageParcel& data, MessageParcel& reply); + void AllocNativeTokenInner(MessageParcel& data, MessageParcel& reply); + void UpdateHapTokenInner(MessageParcel& data, MessageParcel& reply); + void GetHapTokenInfoInner(MessageParcel& data, MessageParcel& reply); + void GetNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply); + void AllocLocalTokenIDInner(MessageParcel& data, MessageParcel& reply); + void GetHapTokenIDInner(MessageParcel& data, MessageParcel& reply); + void CheckNativeDCapInner(MessageParcel& data, MessageParcel& reply); + void GetTokenTypeInner(MessageParcel& data, MessageParcel& reply); + + bool IsAuthorizedCalling() const; + static const int SYSTEM_UID = 1000; + static const int ROOT_UID = 0; + + using RequestFuncType = void (AccessTokenManagerStub::*)(MessageParcel &data, MessageParcel &reply); + std::map requestFuncMap_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_MANAGER_STUB_H diff --git a/services/accesstokenmanager/main/cpp/include/token/accesstoken_id_manager.h b/services/accesstokenmanager/main/cpp/include/token/accesstoken_id_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..b74934975a25efc67d469617e40a78c072298c93 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/token/accesstoken_id_manager.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_TOKEN_ID_MANAGER_H +#define ACCESSTOKEN_TOKEN_ID_MANAGER_H + +#include +#include + +#include "access_token.h" +#include "nocopyable.h" +#include "rwlock.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +static constexpr int TOKEN_RANDOM_MASK = (1 << 24) - 1; +static const int MAX_CREATE_TOKEN_ID_RETRY = 2; + +class AccessTokenIDManager final { +public: + static AccessTokenIDManager& GetInstance(); + virtual ~AccessTokenIDManager() = default; + + int AddTokenId(AccessTokenID id, ATokenTypeEnum type); + AccessTokenID CreateAndRegisterTokenId(ATokenTypeEnum type); + int RegisterTokenId(AccessTokenID id, ATokenTypeEnum type); + void ReleaseTokenId(AccessTokenID id); + ATokenTypeEnum GetTokenIdType(AccessTokenID id); + +private: + AccessTokenIDManager() = default; + DISALLOW_COPY_AND_MOVE(AccessTokenIDManager); + AccessTokenID CreateTokenId(ATokenTypeEnum type) const; + + OHOS::Utils::RWLock tokenIdLock_; + std::set tokenIdSet_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_TOKEN_ID_MANAGER_H diff --git a/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h b/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..7b282ec13e7d9a18109c391d4c4f68b6544026b4 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_TOKEN_INFO_MANAGER_H +#define ACCESSTOKEN_TOKEN_INFO_MANAGER_H + +#include +#include +#include + +#include "access_token.h" +#include "hap_token_info.h" +#include "hap_token_info_inner.h" +#include "native_token_info.h" +#include "native_token_info_inner.h" +#include "nocopyable.h" +#include "rwlock.h" +#include "thread_pool.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class AccessTokenInfoManager final { +public: + static AccessTokenInfoManager& GetInstance(); + ~AccessTokenInfoManager(); + void Init(); + std::shared_ptr GetHapTokenInfoInner(AccessTokenID id); + int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& InfoParcel); + std::shared_ptr GetNativeTokenInfoInner(AccessTokenID id); + int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& InfoParcel); + std::shared_ptr GetHapPermissionPolicySet(AccessTokenID id); + int RemoveTokenInfo(AccessTokenID id); + int CreateHapTokenInfo(const HapInfoParams& info, const HapPolicyParams& policy, AccessTokenIDEx& tokenIdEx); + int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap); + AccessTokenID GetHapTokenID(int userID, const std::string& bundleName, int instIndex); + AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID); + void ProcessNativeTokenInfos(const std::vector>& tokenInfos); + int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParams& policy); + void Dump(std::string& dumpInfo); + void RefreshTokenInfoIfNeeded(); + +private: + AccessTokenInfoManager(); + DISALLOW_COPY_AND_MOVE(AccessTokenInfoManager); + + void InitHapTokenInfos(); + void InitNativeTokenInfos(); + int AddHapTokenInfo(const std::shared_ptr& info); + int AddNativeTokenInfo(const std::shared_ptr& info); + std::string GetHapUniqueStr(const std::shared_ptr& info) const; + std::string GetHapUniqueStr(const int& userID, const std::string& bundleName, const int& instIndex) const; + bool TryUpdateExistNativeToken(const std::shared_ptr& infoPtr); + int AllocNativeToken(const std::shared_ptr& infoPtr); + void StoreAllTokenInfo(); + + OHOS::ThreadPool tokenDataWorker_; + bool hasInited_; + + OHOS::Utils::RWLock hapTokenInfoLock_; + OHOS::Utils::RWLock nativeTokenInfoLock_; + OHOS::Utils::RWLock managerLock_; + + std::map> hapTokenInfoMap_; + std::map hapTokenIdMap_; + std::map> nativeTokenInfoMap_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_TOKEN_INFO_MANAGER_H diff --git a/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h b/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h new file mode 100644 index 0000000000000000000000000000000000000000..53fea91adae84997a3e4c5afdc7f7e4ff7099dc4 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_HAP_TOKEN_INFO_INNER_H +#define ACCESSTOKEN_HAP_TOKEN_INFO_INNER_H + +#include +#include +#include + +#include "access_token.h" +#include "generic_values.h" +#include "hap_token_info.h" +#include "permission_def.h" +#include "permission_policy_set.h" +#include "permission_state_full.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class HapTokenInfoInner final { +public: + HapTokenInfoInner() : ver_(DEFAULT_TOKEN_VERSION), tokenID_(0), tokenAttr_(0), userID_(0), + instIndex_(0), apl_(APL_NORMAL) {}; + virtual ~HapTokenInfoInner() = default; + + void Init(AccessTokenID id, const HapInfoParams& info, const HapPolicyParams& policy); + void Update(const std::string& appIDDesc, const HapPolicyParams& policy); + void TranslateToHapTokenInfo(HapTokenInfo& InfoParcel) const; + void StoreHapInfo(std::vector& hapInfoValues, + std::vector& permDefValues, + std::vector& permStateValues) const; + int RestoreHapTokenInfo(AccessTokenID tokenId, GenericValues& tokenValue, + const std::vector& permDefRes, const std::vector& permStateRes); + + std::shared_ptr GetHapInfoPermissionPolicySet() const; + int GetUserID() const; + std::string GetBundleName() const; + int GetInstIndex() const; + AccessTokenID GetTokenID() const; + void ToString(std::string& info) const; + +private: + void StoreHapBasicInfo(std::vector& valueList) const; + void TranslationIntoGenericValues(GenericValues& outGenericValues) const; + int RestoreHapTokenBasicInfo(const GenericValues& inGenericValues); + + char ver_; + AccessTokenID tokenID_; + AccessTokenAttr tokenAttr_; + int userID_; + std::string bundleName_; + int instIndex_; + std::string appID_; + std::string deviceID_; + ATokenAplEnum apl_; + std::shared_ptr permPolicySet_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_HAP_TOKEN_INFO_INNER_H diff --git a/services/accesstokenmanager/main/cpp/include/token/native_token_info_inner.h b/services/accesstokenmanager/main/cpp/include/token/native_token_info_inner.h new file mode 100644 index 0000000000000000000000000000000000000000..f24c27b59a0fddca082911a970a608d1dc10af3c --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/token/native_token_info_inner.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_NATIVE_TOKEN_INFO_INNER_H +#define ACCESSTOKEN_NATIVE_TOKEN_INFO_INNER_H + +#include "access_token.h" +#include "native_token_info.h" +#include +#include +#include "generic_values.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +static const std::string JSON_PROCESS_NAME = "processName"; +static const std::string JSON_APL = "APL"; +static const std::string JSON_VERSION = "version"; +static const std::string JSON_TOKEN_ID = "tokenId"; +static const std::string JSON_TOKEN_ATTR = "tokenAttr"; +static const std::string JSON_DCAPS = "dcaps"; + +class NativeTokenInfoInner final { +public: + NativeTokenInfoInner() : ver_(DEFAULT_TOKEN_VERSION), tokenID_(0), tokenAttr_(0), apl_(APL_NORMAL) {}; + virtual ~NativeTokenInfoInner() = default; + + void Init(AccessTokenID id, const std::string& processName, ATokenAplEnum apl, + const std::vector& dcap); + void StoreNativeInfo(std::vector& valueList) const; + void TranslateToNativeTokenInfo(NativeTokenInfo& InfoParcel) const; + void SetDcaps(const std::string& dcapStr); + void ToString(std::string& info) const; + int RestoreNativeTokenInfo(AccessTokenID tokenId, const GenericValues& inGenericValues); + void Update(AccessTokenID tokenId, const std::string& processName, + int apl, const std::vector& dcap); + + std::vector GetDcap() const; + AccessTokenID GetTokenID() const; + std::string GetProcessName() const; + bool FromJsonString(const std::string& jsonString); + +private: + int TranslationIntoGenericValues(GenericValues& outGenericValues) const; + std::string DcapToString(const std::vector& dcap) const; + + char ver_; + AccessTokenID tokenID_; + AccessTokenAttr tokenAttr_; + std::string processName_; + ATokenAplEnum apl_; + std::vector dcap_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_NATIVE_TOKEN_INFO_INNER_H diff --git a/services/accesstokenmanager/main/cpp/src/database/data_storage.cpp b/services/accesstokenmanager/main/cpp/src/database/data_storage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..90559c6c21a5eb387454fb2359357496a90e4558 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/database/data_storage.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "data_storage.h" + +#include "sqlite_storage.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +DataStorage& DataStorage::GetRealDataStorage() +{ + return SqliteStorage::GetInstance(); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/services/accesstokenmanager/main/cpp/src/database/data_translator.cpp b/services/accesstokenmanager/main/cpp/src/database/data_translator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f039a1747a3f1f1c0808aee116e60afa506d2c3 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/database/data_translator.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "data_translator.h" + +#include + +#include "accesstoken_log.h" +#include "field_const.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +int DataTranslator::TranslationIntoGenericValues(const PermissionDef& inPermissionDef, GenericValues& outGenericValues) +{ + outGenericValues.Put(FIELD_PERMISSION_NAME, inPermissionDef.permissionName); + outGenericValues.Put(FIELD_BUNDLE_NAME, inPermissionDef.bundleName); + outGenericValues.Put(FIELD_GRANT_MODE, inPermissionDef.grantMode); + outGenericValues.Put(FIELD_AVAILABLE_SCOPE, inPermissionDef.availableScope); + outGenericValues.Put(FIELD_LABEL, inPermissionDef.label); + outGenericValues.Put(FIELD_LABEL_ID, inPermissionDef.labelId); + outGenericValues.Put(FIELD_DESCRIPTION, inPermissionDef.description); + outGenericValues.Put(FIELD_DESCRIPTION_ID, inPermissionDef.descriptionId); + return RET_SUCCESS; +} + +int DataTranslator::TranslationIntoPermissionDef(const GenericValues& inGenericValues, PermissionDef& outPermissionDef) +{ + outPermissionDef.permissionName = inGenericValues.GetString(FIELD_PERMISSION_NAME); + outPermissionDef.bundleName = inGenericValues.GetString(FIELD_BUNDLE_NAME); + outPermissionDef.grantMode = inGenericValues.GetInt(FIELD_GRANT_MODE); + outPermissionDef.availableScope = inGenericValues.GetInt(FIELD_AVAILABLE_SCOPE); + outPermissionDef.label = inGenericValues.GetString(FIELD_LABEL); + outPermissionDef.labelId = inGenericValues.GetInt(FIELD_LABEL_ID); + outPermissionDef.description = inGenericValues.GetString(FIELD_DESCRIPTION); + outPermissionDef.descriptionId = inGenericValues.GetInt(FIELD_DESCRIPTION_ID); + return RET_SUCCESS; +} + +int DataTranslator::TranslationIntoGenericValues(const PermissionStateFull& inPermissionState, + const unsigned int grantIndex, GenericValues& outGenericValues) +{ + if (grantIndex >= inPermissionState.resDeviceID.size() || grantIndex >= inPermissionState.grantStatus.size() + || grantIndex >= inPermissionState.grantFlags.size()) { + return RET_FAILED; + } + outGenericValues.Put(FIELD_PERMISSION_NAME, inPermissionState.permissionName); + outGenericValues.Put(FIELD_DEVICE_ID, inPermissionState.resDeviceID[grantIndex]); + outGenericValues.Put(FIELD_GRANT_IS_GENERAL, inPermissionState.isGeneral ? 1 : 0); + outGenericValues.Put(FIELD_GRANT_STATE, inPermissionState.grantStatus[grantIndex]); + outGenericValues.Put(FIELD_GRANT_FLAG, inPermissionState.grantFlags[grantIndex]); + return RET_SUCCESS; +} + +int DataTranslator::TranslationIntoPermissionStateFull(const GenericValues& inGenericValues, + PermissionStateFull& outPermissionState) +{ + outPermissionState.isGeneral = ((inGenericValues.GetInt(FIELD_GRANT_IS_GENERAL) == 1) ? true : false); + outPermissionState.permissionName = inGenericValues.GetString(FIELD_PERMISSION_NAME); + outPermissionState.resDeviceID.push_back(inGenericValues.GetString(FIELD_DEVICE_ID)); + outPermissionState.grantStatus.push_back((PermissionState)inGenericValues.GetInt(FIELD_GRANT_STATE)); + outPermissionState.grantFlags.push_back(inGenericValues.GetInt(FIELD_GRANT_FLAG)); + return RET_SUCCESS; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/accesstokenmanager/main/cpp/src/database/generic_values.cpp b/services/accesstokenmanager/main/cpp/src/database/generic_values.cpp new file mode 100644 index 0000000000000000000000000000000000000000..db130ace6e4fcbb6e28f8c6da1d7e68eceb220e1 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/database/generic_values.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "generic_values.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +void GenericValues::Put(const std::string& key, int value) +{ + map_.insert(std::make_pair(key, VariantValue(value))); +} + +void GenericValues::Put(const std::string& key, const std::string& value) +{ + map_.insert(std::make_pair(key, VariantValue(value))); +} + +void GenericValues::Put(const std::string& key, const VariantValue& value) +{ + map_.insert(std::make_pair(key, value)); +} + +VariantValue GenericValues::Get(const std::string& key) const +{ + auto iter = map_.find(key); + if (iter == map_.end()) { + return VariantValue(); + } + return iter->second; +} + +int GenericValues::GetInt(const std::string& key) const +{ + auto it = map_.find(key); + if (it == map_.end()) { + return VariantValue::DEFAULT_VALUE; + } + return it->second.GetInt(); +} + +std::string GenericValues::GetString(const std::string& key) const +{ + auto it = map_.find(key); + if (it == map_.end()) { + return std::string(); + } + return it->second.GetString(); +} + +std::vector GenericValues::GetAllKeys() const +{ + std::vector keys; + for (auto it = map_.begin(); it != map_.end(); ++it) { + keys.emplace_back(it->first); + } + return keys; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/services/accesstokenmanager/main/cpp/src/database/sqlite_helper.cpp b/services/accesstokenmanager/main/cpp/src/database/sqlite_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..618b9cf2d64c6c5786fc800f6ba04fedbe4987f2 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/database/sqlite_helper.cpp @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sqlite_helper.h" + +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SqliteHelper"}; +} + +SqliteHelper::SqliteHelper(const std::string& dbName, const std::string& dbPath, int version) + : dbName_(dbName), dbPath_(dbPath), currentVersion_(version), db_(nullptr) +{} + +SqliteHelper::~SqliteHelper() +{} + +void SqliteHelper::Open() +{ + if (db_ != nullptr) { + return; + } + if (dbName_.empty() || dbPath_.empty() || currentVersion_ < 0) { + return; + } + std::string fileName = dbPath_ + dbName_; + int res = sqlite3_open(fileName.c_str(), &db_); + if (res != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to open db: %{public}s", sqlite3_errmsg(db_)); + return; + } + + int version = GetVersion(); + if (version == currentVersion_) { + return; + } + + BeginTransaction(); + if (version == 0) { + OnCreate(); + } else { + if (version < currentVersion_) { + OnUpdate(); + } + } + SetVersion(); + CommitTransaction(); +} + +void SqliteHelper::Close() +{ + if (db_ == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__); + return; + } + int ret = sqlite3_close(db_); + if (ret != SQLITE_OK) { + ACCESSTOKEN_LOG_WARN(LABEL, "sqlite3_close error, ret=%{public}d", ret); + return; + } + db_ = nullptr; +} + +int SqliteHelper::BeginTransaction() const +{ + if (db_ == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__); + return GENERAL_ERROR; + } + char* errorMessage = nullptr; + int result = 0; + int ret = sqlite3_exec(db_, "BEGIN;", nullptr, nullptr, &errorMessage); + if (ret != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: failed, errorMsg: %{public}s", __func__, errorMessage); + result = GENERAL_ERROR; + } + sqlite3_free(errorMessage); + return result; +} + +int SqliteHelper::CommitTransaction() const +{ + if (db_ == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__); + return GENERAL_ERROR; + } + char* errorMessage = nullptr; + int result = 0; + int ret = sqlite3_exec(db_, "COMMIT;", nullptr, nullptr, &errorMessage); + if (ret != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: failed, errorMsg: %{public}s", __func__, errorMessage); + result = GENERAL_ERROR; + } + sqlite3_free(errorMessage); + return result; +} + +int SqliteHelper::RollbackTransaction() const +{ + if (db_ == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__); + return GENERAL_ERROR; + } + int result = 0; + char* errorMessage = nullptr; + int ret = sqlite3_exec(db_, "ROLLBACK;", nullptr, nullptr, &errorMessage); + if (ret != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: failed, errorMsg: %{public}s", __func__, errorMessage); + result = GENERAL_ERROR; + } + sqlite3_free(errorMessage); + return result; +} + +Statement SqliteHelper::Prepare(const std::string& sql) const +{ + return Statement(db_, sql); +} + +int SqliteHelper::ExecuteSql(const std::string& sql) const +{ + if (db_ == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__); + return GENERAL_ERROR; + } + char* errorMessage = nullptr; + int result = 0; + int res = sqlite3_exec(db_, sql.c_str(), nullptr, nullptr, &errorMessage); + if (res != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: failed, errorMsg: %{public}s", __func__, errorMessage); + result = GENERAL_ERROR; + } + sqlite3_free(errorMessage); + return result; +} + +int SqliteHelper::GetVersion() const +{ + if (db_ == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__); + return GENERAL_ERROR; + } + auto statement = Prepare(PRAGMA_VERSION_COMMAND); + int version = 0; + while (statement.Step() == Statement::State::ROW) { + version = statement.GetColumnInt(0); + } + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s: version: %{public}d", __func__, version); + return version; +} + +void SqliteHelper::SetVersion() const +{ + if (db_ == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__); + return; + } + auto statement = Prepare(PRAGMA_VERSION_COMMAND + " = " + std::to_string(currentVersion_)); + statement.Step(); +} + +std::string SqliteHelper::SpitError() const +{ + if (db_ == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__); + return ""; + } + return sqlite3_errmsg(db_); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/services/accesstokenmanager/main/cpp/src/database/sqlite_storage.cpp b/services/accesstokenmanager/main/cpp/src/database/sqlite_storage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..421ab572af0a3fddb3441324abfa663f0e8cdec1 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/database/sqlite_storage.cpp @@ -0,0 +1,368 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sqlite_storage.h" + +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SqliteStorage"}; +} + +SqliteStorage& SqliteStorage::GetInstance() +{ + static SqliteStorage instance; + return instance; +} + +SqliteStorage::~SqliteStorage() +{ + Close(); +} + +void SqliteStorage::OnCreate() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called.", __func__); + CreateHapTokenInfoTable(); + CreateNativeTokenInfoTable(); + CreatePermissionDefinitionTable(); + CreatePermissionStateTable(); +} + +void SqliteStorage::OnUpdate() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called.", __func__); +} + +SqliteStorage::SqliteStorage() : SqliteHelper(DATABASE_NAME, DATABASE_PATH, DATABASE_VERSION) +{ + SqliteTable hapTokenInfoTable; + hapTokenInfoTable.tableName_ = HAP_TOKEN_INFO_TABLE; + hapTokenInfoTable.tableColumnNames_ = { + FIELD_TOKEN_ID, FIELD_USER_ID, + FIELD_BUNDLE_NAME, FIELD_INST_INDEX, + FIELD_APP_ID, FIELD_DEVICE_ID, + FIELD_APL, FIELD_TOKEN_VERSION, + FIELD_TOKEN_ATTR + }; + + SqliteTable NativeTokenInfoTable; + NativeTokenInfoTable.tableName_ = NATIVE_TOKEN_INFO_TABLE; + NativeTokenInfoTable.tableColumnNames_ = { + FIELD_TOKEN_ID, FIELD_PROCESS_NAME, + FIELD_TOKEN_VERSION, FIELD_TOKEN_ATTR, + FIELD_DCAP + }; + + SqliteTable permissionDefTable; + permissionDefTable.tableName_ = PERMISSION_DEF_TABLE; + permissionDefTable.tableColumnNames_ = { + FIELD_TOKEN_ID, FIELD_PERMISSION_NAME, + FIELD_BUNDLE_NAME, FIELD_GRANT_MODE, + FIELD_AVAILABLE_SCOPE, FIELD_LABEL, + FIELD_LABEL_ID, FIELD_DESCRIPTION, + FIELD_DESCRIPTION_ID + }; + + SqliteTable permissionStateTable; + permissionStateTable.tableName_ = PERMISSION_STATE_TABLE; + permissionStateTable.tableColumnNames_ = { + FIELD_TOKEN_ID, FIELD_PERMISSION_NAME, + FIELD_DEVICE_ID, FIELD_GRANT_IS_GENERAL, + FIELD_GRANT_STATE, FIELD_GRANT_FLAG + }; + + dataTypeToSqlTable_ = { + {ACCESSTOKEN_HAP_INFO, hapTokenInfoTable}, + {ACCESSTOKEN_NATIVE_INFO, NativeTokenInfoTable}, + {ACCESSTOKEN_PERMISSION_DEF, permissionDefTable}, + {ACCESSTOKEN_PERMISSION_STATE, permissionStateTable}, + }; + + Open(); +} + +int SqliteStorage::Add(const DataType type, const std::vector& values) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::string prepareSql = CreateInsertPrepareSqlCmd(type); + auto statement = Prepare(prepareSql); + BeginTransaction(); + bool isExecuteSuccessfully = true; + for (auto value : values) { + std::vector columnNames = value.GetAllKeys(); + for (auto columnName : columnNames) { + statement.Bind(columnName, value.Get(columnName)); + } + int ret = statement.Step(); + if (ret != Statement::State::DONE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: failed, errorMsg: %{public}s", __func__, SpitError().c_str()); + isExecuteSuccessfully = false; + } + statement.Reset(); + } + if (!isExecuteSuccessfully) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: rollback transaction.", __func__); + RollbackTransaction(); + return FAILURE; + } + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s: commit transaction.", __func__); + CommitTransaction(); + return SUCCESS; +} + +int SqliteStorage::Remove(const DataType type, const GenericValues& conditions) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::vector columnNames = conditions.GetAllKeys(); + std::string prepareSql = CreateDeletePrepareSqlCmd(type, columnNames); + auto statement = Prepare(prepareSql); + for (auto columnName : columnNames) { + statement.Bind(columnName, conditions.Get(columnName)); + } + int ret = statement.Step(); + return (ret == Statement::State::DONE) ? SUCCESS : FAILURE; +} + +int SqliteStorage::Modify(const DataType type, const GenericValues& modifyValues, const GenericValues& conditions) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::vector modifyColumns = modifyValues.GetAllKeys(); + std::vector conditionColumns = conditions.GetAllKeys(); + std::string prepareSql = CreateUpdatePrepareSqlCmd(type, modifyColumns, conditionColumns); + auto statement = Prepare(prepareSql); + for (auto columnName : modifyColumns) { + statement.Bind(columnName, modifyValues.Get(columnName)); + } + for (auto columnName : conditionColumns) { + statement.Bind(columnName, conditions.Get(columnName)); + } + int ret = statement.Step(); + return (ret == Statement::State::DONE) ? SUCCESS : FAILURE; +} + +int SqliteStorage::Find(const DataType type, std::vector& results) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::string prepareSql = CreateSelectPrepareSqlCmd(type); + auto statement = Prepare(prepareSql); + while (statement.Step() == Statement::State::ROW) { + int columnCount = statement.GetColumnCount(); + GenericValues value; + for (int i = 0; i < columnCount; i++) { + value.Put(statement.GetColumnName(i), statement.GetValue(i)); + } + results.emplace_back(value); + } + return SUCCESS; +} + +int SqliteStorage::RefreshAll(const DataType type, const std::vector& values) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::string deleteSql = CreateDeletePrepareSqlCmd(type); + std::string insertSql = CreateInsertPrepareSqlCmd(type); + auto deleteStatement = Prepare(deleteSql); + auto insertStatement = Prepare(insertSql); + BeginTransaction(); + bool canCommit = deleteStatement.Step() == Statement::State::DONE; + for (auto value : values) { + std::vector columnNames = value.GetAllKeys(); + for (auto columnName : columnNames) { + insertStatement.Bind(columnName, value.Get(columnName)); + } + int ret = insertStatement.Step(); + if (ret != Statement::State::DONE) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: insert failed, errorMsg: %{public}s", __func__, SpitError().c_str()); + canCommit = false; + } + insertStatement.Reset(); + } + if (!canCommit) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: rollback transaction.", __func__); + RollbackTransaction(); + return FAILURE; + } + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s: commit transaction.", __func__); + CommitTransaction(); + return SUCCESS; +} + +std::string SqliteStorage::CreateInsertPrepareSqlCmd(const DataType type) const +{ + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + std::string sql = "insert into " + it->second.tableName_ + " values("; + int i = 1; + for (const auto& columnName : it->second.tableColumnNames_) { + sql.append(":" + columnName); + if (i < (int) it->second.tableColumnNames_.size()) { + sql.append(","); + } + i += 1; + } + sql.append(")"); + return sql; +} + +std::string SqliteStorage::CreateDeletePrepareSqlCmd( + const DataType type, const std::vector& columnNames) const +{ + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + std::string sql = "delete from " + it->second.tableName_ + " where 1 = 1"; + for (auto columnName : columnNames) { + sql.append(" and "); + sql.append(columnName + "=:" + columnName); + } + return sql; +} + +std::string SqliteStorage::CreateUpdatePrepareSqlCmd(const DataType type, const std::vector& modifyColumns, + const std::vector& conditionColumns) const +{ + if (modifyColumns.empty()) { + return std::string(); + } + + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + + std::string sql = "update " + it->second.tableName_ + " set "; + int i = 1; + for (const auto& columnName : modifyColumns) { + sql.append(columnName + "=:" + columnName); + if (i < (int) modifyColumns.size()) { + sql.append(","); + } + i += 1; + } + + if (!conditionColumns.empty()) { + sql.append(" where 1 = 1"); + for (const auto& columnName : conditionColumns) { + sql.append(" and "); + sql.append(columnName + "=:" + columnName); + } + } + return sql; +} + +std::string SqliteStorage::CreateSelectPrepareSqlCmd(const DataType type) const +{ + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + std::string sql = "select * from " + it->second.tableName_; + return sql; +} + +int SqliteStorage::CreateHapTokenInfoTable() const +{ + auto it = dataTypeToSqlTable_.find(DataType::ACCESSTOKEN_HAP_INFO); + if (it == dataTypeToSqlTable_.end()) { + return FAILURE; + } + std::string sql = "create table if not exists "; + sql.append(it->second.tableName_ + " (") + .append(FIELD_TOKEN_ID + " integer not null,") + .append(FIELD_USER_ID + " integer not null,") + .append(FIELD_BUNDLE_NAME + " text not null,") + .append(FIELD_INST_INDEX + " integer not null,") + .append(FIELD_APP_ID + " text not null,") + .append(FIELD_DEVICE_ID + " text not null,") + .append(FIELD_APL + " integer not null,") + .append(FIELD_TOKEN_VERSION + " integer not null,") + .append(FIELD_TOKEN_ATTR + " integer not null,") + .append("primary key(" + FIELD_TOKEN_ID) + .append("))"); + return ExecuteSql(sql); +} + +int SqliteStorage::CreateNativeTokenInfoTable() const +{ + auto it = dataTypeToSqlTable_.find(DataType::ACCESSTOKEN_NATIVE_INFO); + if (it == dataTypeToSqlTable_.end()) { + return FAILURE; + } + std::string sql = "create table if not exists "; + sql.append(it->second.tableName_ + " (") + .append(FIELD_TOKEN_ID + " integer not null,") + .append(FIELD_PROCESS_NAME + " text not null,") + .append(FIELD_TOKEN_VERSION + " integer not null,") + .append(FIELD_TOKEN_ATTR + " integer not null,") + .append(FIELD_DCAP + " text not null,") + .append("primary key(" + FIELD_TOKEN_ID) + .append("))"); + return ExecuteSql(sql); +} + +int SqliteStorage::CreatePermissionDefinitionTable() const +{ + auto it = dataTypeToSqlTable_.find(DataType::ACCESSTOKEN_PERMISSION_DEF); + if (it == dataTypeToSqlTable_.end()) { + return FAILURE; + } + std::string sql = "create table if not exists "; + sql.append(it->second.tableName_ + " (") + .append(FIELD_TOKEN_ID + " integer not null,") + .append(FIELD_PERMISSION_NAME + " text not null,") + .append(FIELD_BUNDLE_NAME + " text not null,") + .append(FIELD_GRANT_MODE + " integer not null,") + .append(FIELD_AVAILABLE_SCOPE + " integer not null,") + .append(FIELD_LABEL + " text not null,") + .append(FIELD_LABEL_ID + " integer not null,") + .append(FIELD_DESCRIPTION + " text not null,") + .append(FIELD_DESCRIPTION_ID + " integer not null,") + .append("primary key(" + FIELD_TOKEN_ID) + .append("," + FIELD_PERMISSION_NAME) + .append("))"); + return ExecuteSql(sql); +} + +int SqliteStorage::CreatePermissionStateTable() const +{ + auto it = dataTypeToSqlTable_.find(DataType::ACCESSTOKEN_PERMISSION_STATE); + if (it == dataTypeToSqlTable_.end()) { + return FAILURE; + } + std::string sql = "create table if not exists "; + sql.append(it->second.tableName_ + " (") + .append(FIELD_TOKEN_ID + " integer not null,") + .append(FIELD_PERMISSION_NAME + " text not null,") + .append(FIELD_DEVICE_ID + " text not null,") + .append(FIELD_GRANT_IS_GENERAL + " integer not null,") + .append(FIELD_GRANT_STATE + " integer not null,") + .append(FIELD_GRANT_FLAG + " integer not null,") + .append("primary key(" + FIELD_TOKEN_ID) + .append("," + FIELD_PERMISSION_NAME) + .append("," + FIELD_DEVICE_ID) + .append("))"); + return ExecuteSql(sql); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/accesstokenmanager/main/cpp/src/database/statement.cpp b/services/accesstokenmanager/main/cpp/src/database/statement.cpp new file mode 100644 index 0000000000000000000000000000000000000000..42d2e3656cee9892ade9ef89d8f3ea5a3dcd3f4c --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/database/statement.cpp @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "statement.h" + +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "Statement"}; +} + +Statement::Statement(sqlite3* db, const std::string& sql) : db_(db), sql_(sql) +{ + if (sqlite3_prepare_v2(db, sql.c_str(), sql.size(), &statement_, nullptr) != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Cannot prepare, errorMsg: %{public}s", sqlite3_errmsg(db_)); + } +} + +Statement::~Statement() +{ + sqlite3_finalize(statement_); + statement_ = nullptr; +} + +void Statement::Bind(const int index, const std::string& text) +{ + if (sqlite3_bind_text(statement_, index, text.c_str(), text.size(), SQLITE_TRANSIENT) != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Cannot bind string, errorMsg: %{public}s", sqlite3_errmsg(db_)); + } +} + +void Statement::Bind(const int index, int value) +{ + if (sqlite3_bind_int(statement_, index, value) != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Cannot bind int, errorMsg: %{public}s", sqlite3_errmsg(db_)); + } +} + +int Statement::GetColumnInt(const int column) const +{ + return sqlite3_column_int(statement_, column); +} + +std::string Statement::GetColumnString(const int column) const +{ + return std::string(reinterpret_cast(sqlite3_column_text(statement_, column))); +} + +std::string Statement::GetColumnName(const int column) const +{ + return sqlite3_column_name(statement_, column); +} + +Statement::State Statement::Step() +{ + int ret = sqlite3_step(statement_); + switch (ret) { + case SQLITE_ROW: + return Statement::State::ROW; + case SQLITE_DONE: + return Statement::State::DONE; + case SQLITE_BUSY: + return Statement::State::BUSY; + case SQLITE_MISUSE: + return Statement::State::MISUSE; + default: + return Statement::State::UNKNOWN; + } +} + +int Statement::GetParameterIndex(const std::string& name) const +{ + return sqlite3_bind_parameter_index(statement_, name.c_str()); +} + +void Statement::Bind(const std::string& tableColumnName, const VariantValue& value) +{ + int index = GetParameterIndex(":" + tableColumnName); + if (value.GetType() == ValueType::TYPE_STRING) { + Bind(index, value.GetString()); + } else if (value.GetType() == ValueType::TYPE_INT) { + Bind(index, value.GetInt()); + } +} + +int Statement::Reset() +{ + return sqlite3_reset(statement_); +} + +int Statement::GetColumnCount() const +{ + return sqlite3_column_count(statement_); +} + +VariantValue Statement::GetValue(const int column) const +{ + int type = sqlite3_column_type(statement_, column); + switch (type) { + case SQLITE_INTEGER: + return VariantValue(GetColumnInt(column)); + case SQLITE_TEXT: + return VariantValue(GetColumnString(column)); + default: + return VariantValue(); + } +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/services/accesstokenmanager/main/cpp/src/database/variant_value.cpp b/services/accesstokenmanager/main/cpp/src/database/variant_value.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3dae3273105551fd698c8f270de4b0d8198d9802 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/database/variant_value.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "variant_value.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +VariantValue::VariantValue() : type_(ValueType::TYPE_NULL) +{} + +VariantValue::~VariantValue() +{} + +VariantValue::VariantValue(int value) : type_(ValueType::TYPE_INT) +{ + value_ = value; +} + +VariantValue::VariantValue(const std::string& value) : type_(ValueType::TYPE_STRING) +{ + value_ = value; +} + +ValueType VariantValue::GetType() const +{ + return type_; +} + +int VariantValue::GetInt() const +{ + if (type_ != ValueType::TYPE_INT) { + return DEFAULT_VALUE; + } + + return std::get(value_); +} + +std::string VariantValue::GetString() const +{ + if (type_ != ValueType::TYPE_STRING) { + return std::string(); + } + + return std::get(value_); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/services/accesstokenmanager/main/cpp/src/permission/permission_definition_cache.cpp b/services/accesstokenmanager/main/cpp/src/permission/permission_definition_cache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9894dac64661c5ade432b78923cc8e6e5642a65 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/permission/permission_definition_cache.cpp @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_definition_cache.h" + +#include "access_token.h" +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "PermissionDefinitionCache" +}; +} + +PermissionDefinitionCache& PermissionDefinitionCache::GetInstance() +{ + static PermissionDefinitionCache instance; + return instance; +} + +PermissionDefinitionCache::PermissionDefinitionCache() +{} + +PermissionDefinitionCache::~PermissionDefinitionCache() +{} + +bool PermissionDefinitionCache::Insert(const PermissionDef& info) +{ + Utils::UniqueWriteGuard cacheGuard(this->cacheLock_); + auto it = permissionDefinitionMap_.find(info.permissionName); + if (it != permissionDefinitionMap_.end()) { + ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: info for permission: %{public}s has been insert, please check!", + __func__, info.permissionName.c_str()); + return false; + } + permissionDefinitionMap_[info.permissionName] = info; + return true; +} + +void PermissionDefinitionCache::DeleteByBundleName(const std::string& bundleName) +{ + Utils::UniqueWriteGuard cacheGuard(this->cacheLock_); + auto it = permissionDefinitionMap_.begin(); + while (it != permissionDefinitionMap_.end()) { + if (bundleName == it->second.bundleName) { + permissionDefinitionMap_.erase(it++); + } else { + ++it; + } + } +} + +int PermissionDefinitionCache::FindByPermissionName(const std::string& permissionName, PermissionDef& info) +{ + Utils::UniqueReadGuard cacheGuard(this->cacheLock_); + auto it = permissionDefinitionMap_.find(permissionName); + if (it == permissionDefinitionMap_.end()) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: can not find definition info for permission: %{public}s", __func__, + permissionName.c_str()); + return RET_FAILED; + } + info = it->second; + return RET_SUCCESS; +} + +bool PermissionDefinitionCache::IsSystemGrantedPermission(const std::string& permissionName) +{ + Utils::UniqueReadGuard cacheGuard(this->cacheLock_); + return IsGrantedModeEqualInner(permissionName, SYSTEM_GRANT); +} + +bool PermissionDefinitionCache::IsUserGrantedPermission(const std::string& permissionName) +{ + Utils::UniqueReadGuard cacheGuard(this->cacheLock_); + return IsGrantedModeEqualInner(permissionName, USER_GRANT); +} + +bool PermissionDefinitionCache::IsGrantedModeEqualInner(const std::string& permissionName, int grantMode) const +{ + auto it = permissionDefinitionMap_.find(permissionName); + if (it == permissionDefinitionMap_.end()) { + return false; + } + return it->second.grantMode == grantMode; +} + +bool PermissionDefinitionCache::HasDefinition(const std::string& permissionName) +{ + Utils::UniqueReadGuard cacheGuard(this->cacheLock_); + return permissionDefinitionMap_.count(permissionName) == 1; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp b/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..35bf38fa4f22783e025b166d5c6fbba8d3fee771 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp @@ -0,0 +1,304 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_manager.h" +#include "access_token.h" +#include "accesstoken_info_manager.h" +#include "accesstoken_log.h" +#include "permission_definition_cache.h" +#include "permission_validator.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "PermissionManager"}; +} + +PermissionManager& PermissionManager::GetInstance() +{ + static PermissionManager instance; + return instance; +} + +PermissionManager::PermissionManager() +{ +} + +PermissionManager::~PermissionManager() +{ +} + +void PermissionManager::AddDefPermissions(const std::vector& permList) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permList size: %{public}d", __func__, permList.size()); + for (auto perm : permList) { + if (!PermissionValidator::IsPermissionDefValid(perm)) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s: invalid permission definition info: %{public}s", __func__, + TransferPermissionDefToString(perm).c_str()); + } else { + PermissionDefinitionCache::GetInstance().Insert(perm); + } + } +} + +void PermissionManager::RemoveDefPermissions(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: 0x%{public}x", __func__, tokenID); + std::shared_ptr tokenInfo = + AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenID); + if (tokenInfo == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params(tokenID: 0x%{public}x)!", __func__, tokenID); + return; + } + std::string bundleName = tokenInfo->GetBundleName(); + PermissionDefinitionCache::GetInstance().DeleteByBundleName(bundleName); +} + +int PermissionManager::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: 0x%{public}x, permissionName: %{public}s", __func__, + tokenID, permissionName.c_str()); + if (!PermissionValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + return PERMISSION_DENIED; + } + if (!PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: no definition for permission: %{public}s!", __func__, permissionName.c_str()); + return PERMISSION_DENIED; + } + std::shared_ptr permPolicySet = + AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenID); + if (permPolicySet == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + return PERMISSION_DENIED; + } + + std::vector permList = permPolicySet->permStateList_; + for (auto perm : permList) { + if (perm.permissionName == permissionName) { + return QueryPermissionStatus(perm); + } + } + return PERMISSION_DENIED; +} + +int PermissionManager::GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permissionName: %{public}s", __func__, permissionName.c_str()); + if (!PermissionValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + return RET_FAILED; + } + if (!PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: no definition for permission: %{public}s!", __func__, permissionName.c_str()); + return RET_FAILED; + } + return PermissionDefinitionCache::GetInstance().FindByPermissionName(permissionName, permissionDefResult); +} + +int PermissionManager::GetDefPermissions(AccessTokenID tokenID, std::vector& permList) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: 0x%{public}x", __func__, tokenID); + std::shared_ptr permPolicySet = + AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenID); + if (permPolicySet == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + return RET_FAILED; + } + std::vector permListGet = permPolicySet->permList_; + permList.assign(permListGet.begin(), permListGet.end()); + return RET_SUCCESS; +} + +int PermissionManager::GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: 0x%{public}x, isSystemGrant: %{public}d", + __func__, tokenID, isSystemGrant); + std::shared_ptr permPolicySet = + AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenID); + if (permPolicySet == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + return RET_FAILED; + } + + GrantMode mode = isSystemGrant ? SYSTEM_GRANT : USER_GRANT; + std::vector permList = permPolicySet->permStateList_; + for (auto perm : permList) { + PermissionDef permDef; + GetDefPermission(perm.permissionName, permDef); + if (permDef.grantMode == mode) { + reqPermList.emplace_back(perm); + } + } + return RET_SUCCESS; +} + +int PermissionManager::GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: 0x%{public}x, permissionName: %{public}s", + __func__, tokenID, permissionName.c_str()); + if (!PermissionValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + return DEFAULT_PERMISSION_FLAGS; + } + if (!PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: no definition for permission: %{public}s!", __func__, permissionName.c_str()); + return DEFAULT_PERMISSION_FLAGS; + } + std::shared_ptr permPolicySet = + AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenID); + if (permPolicySet == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + return DEFAULT_PERMISSION_FLAGS; + } + + std::vector permList = permPolicySet->permStateList_; + for (auto perm : permList) { + if (perm.permissionName == permissionName) { + return QueryPermissionFlag(perm); + } + } + return DEFAULT_PERMISSION_FLAGS; +} + + +int PermissionManager::UpdatePermissionStatus(PermissionStateFull& permStat, bool isGranted, int flag) +{ + if (permStat.isGeneral == true) { + permStat.grantStatus[0] = isGranted ? PERMISSION_GRANTED : PERMISSION_DENIED; + permStat.grantFlags[0] = flag; + } + return RET_FAILED; +} + +void PermissionManager::UpdateTokenPermissionState( + AccessTokenID tokenID, const std::string& permissionName, bool isGranted, int flag) +{ + std::shared_ptr permPolicySet = + AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenID); + if (permPolicySet == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + return; + } + + std::vector& permList = permPolicySet->permStateList_; + for (auto& perm : permList) { + if (perm.permissionName == permissionName) { + UpdatePermissionStatus(perm, isGranted, flag); + break; + } + } +} + +void PermissionManager::GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s called, tokenID: 0x%{public}x, permissionName: %{public}s, flag: %{public}d", + __func__, tokenID, permissionName.c_str(), flag); + if (!PermissionValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + return; + } + if (!PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: no definition for permission: %{public}s!", __func__, permissionName.c_str()); + return; + } + if (!PermissionValidator::IsPermissionFlagValid(flag)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + return; + } + UpdateTokenPermissionState(tokenID, permissionName, true, flag); +} + +void PermissionManager::RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s called, tokenID: 0x%{public}x, permissionName: %{public}s, flag: %{public}d", + __func__, tokenID, permissionName.c_str(), flag); + if (!PermissionValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + return; + } + if (!PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: no definition for permission: %{public}s!", __func__, permissionName.c_str()); + return; + } + if (!PermissionValidator::IsPermissionFlagValid(flag)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + return; + } + UpdateTokenPermissionState(tokenID, permissionName, false, flag); +} + +void PermissionManager::ClearUserGrantedPermissionState(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: 0x%{public}x", __func__, tokenID); + std::shared_ptr permPolicySet = + AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenID); + if (permPolicySet == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + return; + } + + std::vector& permList = permPolicySet->permStateList_; + for (auto& perm : permList) { + PermissionDef permDef; + bool isGranted; + GetDefPermission(perm.permissionName, permDef); + isGranted = (permDef.grantMode == SYSTEM_GRANT) ? true : false; + UpdatePermissionStatus(perm, isGranted, DEFAULT_PERMISSION_FLAGS); + } +} + +int PermissionManager::QueryPermissionFlag(const PermissionStateFull& permStat) +{ + if (permStat.isGeneral == true) { + return permStat.grantFlags[0]; + } + return DEFAULT_PERMISSION_FLAGS; +} + +int PermissionManager::QueryPermissionStatus(const PermissionStateFull& permStat) +{ + if (permStat.isGeneral == true) { + return permStat.grantStatus[0]; + } + return PERMISSION_DENIED; +} + +std::string PermissionManager::TransferPermissionDefToString(const PermissionDef& inPermissionDef) +{ + std::string infos; + infos.append(R"({"permissionName": ")" + inPermissionDef.permissionName + R"(")"); + infos.append(R"(, "bundleName": ")" + inPermissionDef.bundleName + R"(")"); + infos.append(R"(, "grantMode": )" + std::to_string(inPermissionDef.grantMode)); + infos.append(R"(, "availableScope": )" + std::to_string(inPermissionDef.availableScope)); + infos.append(R"(, "label": ")" + inPermissionDef.label + R"(")"); + infos.append(R"(, "labelId": )" + std::to_string(inPermissionDef.labelId)); + infos.append(R"(, "description": ")" + inPermissionDef.description + R"(")"); + infos.append(R"(, "descriptionId": )" + std::to_string(inPermissionDef.descriptionId)); + infos.append("}"); + return infos; +} +} // namespace AccessToken +} // namespace Security +} diff --git a/services/accesstokenmanager/main/cpp/src/permission/permission_policy_set.cpp b/services/accesstokenmanager/main/cpp/src/permission/permission_policy_set.cpp new file mode 100644 index 0000000000000000000000000000000000000000..176e4afff8a509f0c099d84f0bf86ce136e680b8 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/permission/permission_policy_set.cpp @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_policy_set.h" + +#include "accesstoken_log.h" +#include "data_storage.h" +#include "data_translator.h" +#include "field_const.h" +#include "permission_validator.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "PermissionPolicySet"}; +} + +std::shared_ptr PermissionPolicySet::BuildPermissionPolicySet( + AccessTokenID tokenId, const std::vector& permList, + const std::vector& permStateList) +{ + std::shared_ptr policySet = std::make_shared(); + if (policySet != nullptr) { + PermissionValidator::FilterInvalidPermisionDef(permList, policySet->permList_); + PermissionValidator::FilterInvalidPermisionState(permStateList, policySet->permStateList_); + policySet->tokenId_ = tokenId; + } + return policySet; +} + +void PermissionPolicySet::UpdatePermDef(PermissionDef& permOld, const PermissionDef& permNew) +{ + permOld.bundleName = permNew.bundleName; + permOld.grantMode = permNew.grantMode; + permOld.availableScope = permNew.availableScope; + permOld.label = permNew.label; + permOld.labelId = permNew.labelId; + permOld.description = permNew.description; + permOld.descriptionId = permNew.descriptionId; +} + +void PermissionPolicySet::UpdatePermStateFull(PermissionStateFull& permOld, const PermissionStateFull& permNew) +{ + if (permOld.isGeneral != permNew.isGeneral) { + permOld.resDeviceID.clear(); + permOld.grantStatus.clear(); + permOld.grantFlags.clear(); + permOld.isGeneral = permNew.isGeneral; + } +} + +void PermissionPolicySet::Update(const std::vector& permList, + const std::vector& permStateList) +{ + for (const PermissionDef& permNew : permList) { + for (PermissionDef& permOld : permList_) { + if (permNew.permissionName == permOld.permissionName) { + UpdatePermDef(permOld, permNew); + break; + } + } + permList_.emplace_back(permNew); + } + + for (const PermissionStateFull& permStateNew : permStateList) { + for (PermissionStateFull& permStateOld : permStateList_) { + if (permStateNew.permissionName == permStateOld.permissionName) { + UpdatePermStateFull(permStateOld, permStateNew); + break; + } + } + permStateList_.emplace_back(permStateNew); + } +} + +std::shared_ptr PermissionPolicySet::RestorePermissionPolicy(AccessTokenID tokenId, + const std::vector& permDefRes, const std::vector& permStateRes) +{ + std::shared_ptr policySet = std::make_shared(); + if (policySet == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x new failed.", __func__, tokenId); + return nullptr; + } + policySet->tokenId_ = tokenId; + + for (GenericValues defValue : permDefRes) { + if ((AccessTokenID)defValue.GetInt(FIELD_TOKEN_ID) == tokenId) { + PermissionDef def; + DataTranslator::TranslationIntoPermissionDef(defValue, def); + policySet->permList_.emplace_back(def); + } + } + + for (GenericValues stateValue : permStateRes) { + if ((AccessTokenID)stateValue.GetInt(FIELD_TOKEN_ID) == tokenId) { + PermissionStateFull state; + DataTranslator::TranslationIntoPermissionStateFull(stateValue, state); + MergePermissionStateFull(policySet->permStateList_, state); + } + } + return policySet; +} + +void PermissionPolicySet::MergePermissionStateFull(std::vector& permStateList, + const PermissionStateFull& state) +{ + for (auto iter = permStateList.begin(); iter != permStateList.end(); iter++) { + if (state.permissionName == iter->permissionName) { + iter->resDeviceID.emplace_back(state.resDeviceID[0]); + iter->grantStatus.emplace_back(state.grantStatus[0]); + iter->grantFlags.emplace_back(state.grantFlags[0]); + return; + } + } + permStateList.emplace_back(state); +} + +void PermissionPolicySet::StorePermissionDef(std::vector& valueList) const +{ + for (auto permissionDef : permList_) { + GenericValues genericValues; + genericValues.Put(FIELD_TOKEN_ID, tokenId_); + DataTranslator::TranslationIntoGenericValues(permissionDef, genericValues); + valueList.emplace_back(genericValues); + } +} + +void PermissionPolicySet::StorePermissionState(std::vector& valueList) const +{ + for (auto permissionState : permStateList_) { + if (permissionState.isGeneral) { + GenericValues genericValues; + genericValues.Put(FIELD_TOKEN_ID, tokenId_); + DataTranslator::TranslationIntoGenericValues(permissionState, 0, genericValues); + valueList.emplace_back(genericValues); + continue; + } + + unsigned int stateSize = permissionState.resDeviceID.size(); + for (unsigned int i = 0; i < stateSize; i++) { + GenericValues genericValues; + genericValues.Put(FIELD_TOKEN_ID, tokenId_); + DataTranslator::TranslationIntoGenericValues(permissionState, i, genericValues); + valueList.emplace_back(genericValues); + } + } +} + +void PermissionPolicySet::StorePermissionPolicySet(std::vector& permDefValueList, + std::vector& permStateValueList) const +{ + StorePermissionDef(permDefValueList); + StorePermissionState(permStateValueList); +} + +void PermissionPolicySet::PermDefToString(const PermissionDef& def, std::string& info) const +{ + info.append(R"({"permissionName": ")" + def.permissionName + R"(")"); + info.append(R"(, "bundleName": ")" + def.bundleName + R"(")"); + info.append(R"(, "grantMode": )" + std::to_string(def.grantMode)); + info.append(R"(, "availableScope": )" + std::to_string(def.availableScope)); + info.append(R"(, "label": ")" + def.label + R"(")"); + info.append(R"(, "labelId": )" + std::to_string(def.labelId)); + info.append(R"(, "description": ")" + def.description + R"(")"); + info.append(R"(, "descriptionId": )" + std::to_string(def.descriptionId)); + info.append(R"(})"); +} + +void PermissionPolicySet::PermStateFullToString(const PermissionStateFull& state, std::string& info) const +{ + info.append(R"({"permissionName": ")" + state.permissionName + R"(")"); + info.append(R"(, "isGeneral": )" + std::to_string(state.isGeneral)); + + info.append(R"(, "resDeviceIDList": [ )"); + for (auto iter = state.resDeviceID.begin(); iter != state.resDeviceID.end(); iter++) { + info.append(R"({"resDeviceID": ")" + *iter + R"("})"); + if (iter != (state.resDeviceID.end() - 1)) { + info.append(","); + } + } + + info.append(R"(], "grantStatusList": [)"); + for (auto iter = state.grantStatus.begin(); iter != state.grantStatus.end(); iter++) { + info.append(R"({"grantStatus": )" + std::to_string(*iter) + "}"); + if (iter != (state.grantStatus.end() - 1)) { + info.append(","); + } + } + + info.append(R"(], "grantFlagsList": [)"); + for (auto iter = state.grantFlags.begin(); iter != state.grantFlags.end(); iter++) { + info.append(R"({"grantFlag": )" + std::to_string(*iter) + "}"); + if (iter != (state.grantFlags.end() - 1)) { + info.append(","); + } + } + + info.append(R"(]})"); +} + +void PermissionPolicySet::ToString(std::string& info) const +{ + info.append(R"(, "permDefList": [)"); + for (auto iter = permList_.begin(); iter != permList_.end(); iter++) { + PermDefToString(*iter, info); + if (iter != (permList_.end() - 1)) { + info.append(","); + } + } + info.append("]"); + + info.append(R"(, "permStateList": [)"); + for (auto iter = permStateList_.begin(); iter != permStateList_.end(); iter++) { + PermStateFullToString(*iter, info); + if (iter != (permStateList_.end() - 1)) { + info.append(","); + } + } + info.append("]"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/accesstokenmanager/main/cpp/src/permission/permission_validator.cpp b/services/accesstokenmanager/main/cpp/src/permission/permission_validator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..47f39b62e938bf5f973cf06a17d82f8a6b778283 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/permission/permission_validator.cpp @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "permission_validator.h" + +#include + +#include "access_token.h" +#include "data_validator.h" +#include "permission_definition_cache.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool PermissionValidator::IsGrantModeValid(int grantMode) +{ + return grantMode == GrantMode::SYSTEM_GRANT || grantMode == GrantMode::USER_GRANT; +} + +bool PermissionValidator::IsAvailableScopeValid(int availableScope) +{ + return availableScope == AvailableScope::AVAILABLE_SCOPE_ALL || + availableScope == AvailableScope::AVAILABLE_SCOPE_RESTRICTED || + availableScope == AvailableScope::AVAILABLE_SCOPE_SIGNATURE; +} + +bool PermissionValidator::IsGrantStatusValid(int grantStaus) +{ + return grantStaus == PermissionState::PERMISSION_GRANTED || grantStaus == PermissionState::PERMISSION_DENIED; +} + +bool PermissionValidator::IsPermissionFlagValid(int flag) +{ + return flag == PermissionFlag::PERMISSION_USER_SET || + flag == PermissionFlag::PERMISSION_USER_FIXED || + flag == PermissionFlag::PERMISSION_SYSTEM_FIXED; +} + +bool PermissionValidator::IsPermissionNameValid(const std::string& permissionName) +{ + return DataValidator::IsPermissionNameValid(permissionName); +} + +bool PermissionValidator::IsPermissionDefValid(const PermissionDef& permDef) +{ + if (!DataValidator::IsPermissionNameValid(permDef.permissionName)) { + return false; + } + if (!IsGrantModeValid(permDef.grantMode)) { + return false; + } + return IsAvailableScopeValid(permDef.availableScope); +} + +bool PermissionValidator::IsPermissionStateValid(const PermissionStateFull& permState) +{ + if (!DataValidator::IsPermissionNameValid(permState.permissionName)) { + return false; + } + + size_t resDevIdSize = permState.resDeviceID.size(); + size_t grantStatSize = permState.grantStatus.size(); + size_t grantFlagSize = permState.grantFlags.size(); + if ((grantStatSize != resDevIdSize) || (grantFlagSize != resDevIdSize)) { + return false; + } + + for (int i = 0; i < resDevIdSize; i++) { + if (!IsGrantStatusValid(permState.grantStatus[i]) || + !IsPermissionFlagValid(permState.grantFlags[i])) { + return false; + } + } + return true; +} + + +void PermissionValidator::FilterInvalidPermisionDef( + const std::vector& permList, std::vector& result) +{ + std::set permDefSet; + for (auto it = permList.begin(); it != permList.end(); ++it) { + std::string permName = it->permissionName; + if (!IsPermissionDefValid(*it) || permDefSet.count(permName) != 0) { + continue; + } + permDefSet.insert(permName); + result.emplace_back(*it); + } +} + +void PermissionValidator::DeduplicateResDevID(const PermissionStateFull& permState, PermissionStateFull& result) +{ + std::set resDevId; + auto stateIter = permState.grantStatus.begin(); + auto flagIter = permState.grantFlags.begin(); + for (auto it = permState.resDeviceID.begin(); it != permState.resDeviceID.end(); ++it, ++stateIter, ++flagIter) { + if (resDevId.count(*it) != 0) { + continue; + } + resDevId.insert(*it); + result.resDeviceID.emplace_back(*it); + result.grantStatus.emplace_back(*stateIter); + result.grantFlags.emplace_back(*flagIter); + ++stateIter; + ++flagIter; + } + result.permissionName = permState.permissionName; + result.isGeneral = permState.isGeneral; +} + +void PermissionValidator::FilterInvalidPermisionState( + const std::vector& permList, std::vector& result) +{ + std::set permStateSet; + for (auto it = permList.begin(); it != permList.end(); ++it) { + std::string permName = it->permissionName; + PermissionStateFull res; + if (!IsPermissionStateValid(*it) || permStateSet.count(permName) != 0) { + continue; + } + DeduplicateResDevID(*it, res); + permStateSet.insert(permName); + result.emplace_back(res); + } +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0c17654209b903a87aaf8de8fe54e2029f5f829 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp @@ -0,0 +1,246 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_manager_service.h" + +#include "access_token.h" +#include "accesstoken_id_manager.h" +#include "accesstoken_info_manager.h" +#include "accesstoken_log.h" +#include "hap_token_info.h" +#include "hap_token_info_inner.h" +#include "native_token_info_inner.h" +#include "permission_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenManagerService" +}; +} + +const bool REGISTER_RESULT = + SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); + +AccessTokenManagerService::AccessTokenManagerService() + : SystemAbility(SA_ID_ACCESSTOKEN_MANAGER_SERVICE, true), state_(ServiceRunningState::STATE_NOT_START) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "AccessTokenManagerService()"); +} + +AccessTokenManagerService::~AccessTokenManagerService() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "~AccessTokenManagerService()"); +} + +void AccessTokenManagerService::OnStart() +{ + if (state_ == ServiceRunningState::STATE_RUNNING) { + ACCESSTOKEN_LOG_INFO(LABEL, "AccessTokenManagerService has already started!"); + return; + } + ACCESSTOKEN_LOG_INFO(LABEL, "AccessTokenManagerService is starting"); + if (!Initialize()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to initialize"); + return; + } + state_ = ServiceRunningState::STATE_RUNNING; + bool ret = Publish(DelayedSingleton::GetInstance().get()); + if (!ret) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to publish service!"); + return; + } + ACCESSTOKEN_LOG_INFO(LABEL, "Congratulations, AccessTokenManagerService start successfully!"); +} + +void AccessTokenManagerService::OnStop() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "stop service"); + state_ = ServiceRunningState::STATE_NOT_START; +} + +int AccessTokenManagerService::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s called, tokenID: 0x%{public}x, permissionName: %{public}s", __func__, + tokenID, permissionName.c_str()); + return PermissionManager::GetInstance().VerifyAccessToken(tokenID, permissionName); +} + +int AccessTokenManagerService::GetDefPermission( + const std::string& permissionName, PermissionDefParcel& permissionDefResult) +{ + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s called, permissionName: %{public}s", __func__, permissionName.c_str()); + return PermissionManager::GetInstance().GetDefPermission(permissionName, permissionDefResult.permissionDef); +} + +int AccessTokenManagerService::GetDefPermissions(AccessTokenID tokenID, std::vector& permList) +{ + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s called, tokenID: 0x%{public}x", __func__, tokenID); + std::vector permVec; + int ret = PermissionManager::GetInstance().GetDefPermissions(tokenID, permVec); + for (auto perm : permVec) { + PermissionDefParcel permPrcel; + permPrcel.permissionDef = perm; + permList.emplace_back(permPrcel); + } + return ret; +} + +int AccessTokenManagerService::GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) +{ + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s called, tokenID: 0x%{public}x, isSystemGrant: %{public}d", __func__, tokenID, isSystemGrant); + + std::vector permList; + int ret = PermissionManager::GetInstance().GetReqPermissions(tokenID, permList, isSystemGrant); + + for (auto& perm : permList) { + PermissionStateFullParcel permPrcel; + permPrcel.permStatFull = perm; + reqPermList.emplace_back(permPrcel); + } + return ret; +} + +int AccessTokenManagerService::GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s called, tokenID: 0x%{public}x, permissionName: %{public}s", __func__, + tokenID, permissionName.c_str()); + return PermissionManager::GetInstance().GetPermissionFlag(tokenID, permissionName); +} + +int AccessTokenManagerService::GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s called, tokenID: 0x%{public}x, permissionName: %{public}s, flag: %{public}d", __func__, + tokenID, permissionName.c_str(), flag); + PermissionManager::GetInstance().GrantPermission(tokenID, permissionName, flag); + AccessTokenInfoManager::GetInstance().RefreshTokenInfoIfNeeded(); + return RET_SUCCESS; +} + +int AccessTokenManagerService::RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s called, tokenID: 0x%{public}x, permissionName: %{public}s, flag: %{public}d", __func__, + tokenID, permissionName.c_str(), flag); + PermissionManager::GetInstance().RevokePermission(tokenID, permissionName, flag); + AccessTokenInfoManager::GetInstance().RefreshTokenInfoIfNeeded(); + return RET_SUCCESS; +} + +int AccessTokenManagerService::ClearUserGrantedPermissionState(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s called, tokenID: 0x%{public}x", __func__, tokenID); + PermissionManager::GetInstance().ClearUserGrantedPermissionState(tokenID); + AccessTokenInfoManager::GetInstance().RefreshTokenInfoIfNeeded(); + return RET_SUCCESS; +} + +AccessTokenIDEx AccessTokenManagerService::AllocHapToken(const HapInfoParcel& info, const HapPolicyParcel& policy) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + AccessTokenIDEx tokenIdEx; + tokenIdEx.tokenIDEx = 0LL; + + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo( + info.hapInfoParameter, policy.hapPolicyParameter, tokenIdEx); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, hap token info create failed", __func__); + } + return tokenIdEx; +} + +int AccessTokenManagerService::DeleteToken(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s called, tokenID: 0x%{public}x", __func__, tokenID); + return AccessTokenInfoManager::GetInstance().RemoveTokenInfo(tokenID); +} + +int AccessTokenManagerService::GetTokenType(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: 0x%{public}x", __func__, tokenID); + return AccessTokenIDManager::GetInstance().GetTokenIdType(tokenID); +} + +int AccessTokenManagerService::CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: 0x%{public}x, dcap: %{public}s", + __func__, tokenID, dcap.c_str()); + return AccessTokenInfoManager::GetInstance().CheckNativeDCap(tokenID, dcap); +} + +AccessTokenID AccessTokenManagerService::GetHapTokenID(int userID, const std::string& bundleName, int instIndex) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, userID: %{public}d, bundleName: %{public}s, instIndex: %{public}d", + __func__, userID, bundleName.c_str(), instIndex); + return AccessTokenInfoManager::GetInstance().GetHapTokenID(userID, bundleName, instIndex); +} + +AccessTokenID AccessTokenManagerService::AllocLocalTokenID( + const std::string& remoteDeviceID, AccessTokenID remoteTokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, remoteDeviceID: %{public}s, remoteTokenID: %{public}d", + __func__, remoteDeviceID.c_str(), remoteTokenID); + return AccessTokenInfoManager::GetInstance().AllocLocalTokenID(remoteDeviceID, remoteTokenID); +} + +int AccessTokenManagerService::UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, + const HapPolicyParcel& policyParcel) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: 0x%{public}x", __func__, tokenID); + + return AccessTokenInfoManager::GetInstance().UpdateHapToken(tokenID, appIDDesc, + policyParcel.hapPolicyParameter); +} + +int AccessTokenManagerService::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfoParcel& InfoParcel) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: 0x%{public}x", __func__, tokenID); + + HapTokenInfo hapTokenInfo; + AccessTokenInfoManager::GetInstance().GetHapTokenInfo(tokenID, hapTokenInfo); + InfoParcel.hapTokenInfoParams = hapTokenInfo; + return RET_SUCCESS; +} + +int AccessTokenManagerService::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfoParcel& InfoParcel) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: 0x%{public}x", __func__, tokenID); + + NativeTokenInfo nativeTokenInfo; + AccessTokenInfoManager::GetInstance().GetNativeTokenInfo(tokenID, nativeTokenInfo); + InfoParcel.nativeTokenInfoParams = nativeTokenInfo; + + return RET_SUCCESS; +} + +bool AccessTokenManagerService::Initialize() const +{ + AccessTokenInfoManager::GetInstance().Init(); + return true; +} +} // namespace AccessToken +} // namespace Security +} diff --git a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cc6e8e07f64b3f6fc2935f56732fc53055f37877 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp @@ -0,0 +1,334 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_manager_stub.h" + +#include "accesstoken_log.h" + +#include "ipc_skeleton.h" +#include "string_ex.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenManagerStub"}; +} + +int32_t AccessTokenManagerStub::OnRemoteRequest( + uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, code: %{public}d", __func__, code); + std::u16string descriptor = data.ReadInterfaceToken(); + if (descriptor != IAccessTokenManager::GetDescriptor()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "get unexpect descriptor: %{public}s", Str16ToStr8(descriptor).c_str()); + return -1; + } + auto itFunc = requestFuncMap_.find(code); + if (itFunc != requestFuncMap_.end()) { + auto requestFunc = itFunc->second; + if (requestFunc != nullptr) { + (this->*requestFunc)(data, reply); + } else { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } + return NO_ERROR; +} + +void AccessTokenManagerStub::DeleteTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + int result = this->DeleteToken(tokenID); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::VerifyAccessTokenInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenID = data.ReadUint32(); + std::string permissionName = data.ReadString(); + int result = this->VerifyAccessToken(tokenID, permissionName); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetDefPermissionInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + std::string permissionName = data.ReadString(); + PermissionDefParcel permissionDefParcel; + int result = this->GetDefPermission(permissionName, permissionDefParcel); + reply.WriteParcelable(&permissionDefParcel); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetDefPermissionsInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + std::vector permList; + + int result = this->GetDefPermissions(tokenID, permList); + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permList size: %{public}d", __func__, (int) permList.size()); + reply.WriteInt32(permList.size()); + for (auto permDef : permList) { + reply.WriteParcelable(&permDef); + } + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetReqPermissionsInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + int isSystemGrant = data.ReadInt32(); + std::vector permList; + + int result = this->GetReqPermissions(tokenID, permList, isSystemGrant); + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permList size: %{public}d", __func__, (int) permList.size()); + reply.WriteInt32(permList.size()); + for (auto permDef : permList) { + reply.WriteParcelable(&permDef); + } + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetPermissionFlagInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenID = data.ReadUint32(); + std::string permissionName = data.ReadString(); + int result = this->GetPermissionFlag(tokenID, permissionName); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GrantPermissionInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + std::string permissionName = data.ReadString(); + int flag = data.ReadInt32(); + int result = this->GrantPermission(tokenID, permissionName, flag); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::RevokePermissionInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + std::string permissionName = data.ReadString(); + int flag = data.ReadInt32(); + int result = this->RevokePermission(tokenID, permissionName, flag); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::ClearUserGrantedPermissionStateInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + int result = this->ClearUserGrantedPermissionState(tokenID); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::AllocHapTokenInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenIDEx res = {0}; + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + + sptr hapInfoParcel = data.ReadParcelable(); + sptr hapPolicyParcel = data.ReadParcelable(); + + res = this->AllocHapToken(*hapInfoParcel, *hapPolicyParcel); + reply.WriteUint64(res.tokenIDEx); +} + +void AccessTokenManagerStub::GetTokenTypeInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + int result = this->GetTokenType(tokenID); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::CheckNativeDCapInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + std::string dCap = data.ReadString(); + int result = this->CheckNativeDCap(tokenID, dCap); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetHapTokenIDInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + int userID = data.ReadInt32(); + std::string bundleName = data.ReadString(); + int instIndex = data.ReadInt32(); + AccessTokenID result = this->GetHapTokenID(userID, bundleName, instIndex); + reply.WriteUint32(result); +} + +void AccessTokenManagerStub::AllocLocalTokenIDInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + std::string remoteDeviceID = data.ReadString(); + AccessTokenID remoteTokenID = data.ReadUint32(); + AccessTokenID result = this->AllocLocalTokenID(remoteDeviceID, remoteTokenID); + reply.WriteUint32(result); +} + +void AccessTokenManagerStub::UpdateHapTokenInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + std::string appIDDesc = data.ReadString(); + sptr policyParcel = data.ReadParcelable(); + + int32_t result = this->UpdateHapToken(tokenID, appIDDesc, *policyParcel); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + HapTokenInfoParcel hapTokenInfoParcel; + AccessTokenID tokenID = data.ReadUint32(); + int result = this->GetHapTokenInfo(tokenID, hapTokenInfoParcel); + reply.WriteParcelable(&hapTokenInfoParcel); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + NativeTokenInfoParcel nativeTokenInfoParcel; + int result = this->GetNativeTokenInfo(tokenID, nativeTokenInfoParcel); + reply.WriteParcelable(&nativeTokenInfoParcel); + reply.WriteInt32(result); +} + +bool AccessTokenManagerStub::IsAuthorizedCalling() const +{ + int callingUid = IPCSkeleton::GetCallingUid(); + ACCESSTOKEN_LOG_INFO(LABEL, "Calling uid: %{public}d", callingUid); + return callingUid == SYSTEM_UID || callingUid == ROOT_UID; +} + +AccessTokenManagerStub::AccessTokenManagerStub() +{ + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::VERIFY_ACCESSTOKEN)] = + &AccessTokenManagerStub::VerifyAccessTokenInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_DEF_PERMISSION)] = + &AccessTokenManagerStub::GetDefPermissionInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_DEF_PERMISSIONS)] = + &AccessTokenManagerStub::GetDefPermissionsInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_REQ_PERMISSIONS)] = + &AccessTokenManagerStub::GetReqPermissionsInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_PERMISSION_FLAG)] = + &AccessTokenManagerStub::GetPermissionFlagInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GRANT_PERMISSION)] = + &AccessTokenManagerStub::GrantPermissionInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::REVOKE_PERMISSION)] = + &AccessTokenManagerStub::RevokePermissionInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::CLEAR_USER_GRANT_PERMISSION)] = + &AccessTokenManagerStub::ClearUserGrantedPermissionStateInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::ALLOC_TOKEN_HAP)] = + &AccessTokenManagerStub::AllocHapTokenInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::TOKEN_DELETE)] = + &AccessTokenManagerStub::DeleteTokenInfoInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_TOKEN_TYPE)] = + &AccessTokenManagerStub::GetTokenTypeInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::CHECK_NATIVE_DCAP)] = + &AccessTokenManagerStub::CheckNativeDCapInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_HAP_TOKEN_ID)] = + &AccessTokenManagerStub::GetHapTokenIDInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::ALLOC_LOCAL_TOKEN_ID)] = + &AccessTokenManagerStub::AllocLocalTokenIDInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_NATIVE_TOKENINFO)] = + &AccessTokenManagerStub::GetNativeTokenInfoInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_HAP_TOKENINFO)] = + &AccessTokenManagerStub::GetHapTokenInfoInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::UPDATE_HAP_TOKEN)] = + &AccessTokenManagerStub::UpdateHapTokenInner; +} + +AccessTokenManagerStub::~AccessTokenManagerStub() +{ + requestFuncMap_.clear(); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/accesstokenmanager/main/cpp/src/token/accesstoken_id_manager.cpp b/services/accesstokenmanager/main/cpp/src/token/accesstoken_id_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bdd34a724f956f6ef0dad6288a25d93954a2d9b9 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/token/accesstoken_id_manager.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_id_manager.h" + +#include + +#include "accesstoken_log.h" +#include "data_validator.h" +#include "random.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenIDManager"}; +} + +ATokenTypeEnum AccessTokenIDManager::GetTokenIdType(AccessTokenID id) +{ + { + Utils::UniqueReadGuard idGuard(this->tokenIdLock_); + if (tokenIdSet_.count(id) == 0) { + return TOKEN_INVALID; + } + } + AccessTokenIDInner *idInner = (AccessTokenIDInner *)&id; + return (ATokenTypeEnum)idInner->type; +} + +int AccessTokenIDManager::RegisterTokenId(AccessTokenID id, ATokenTypeEnum type) +{ + AccessTokenIDInner *idInner = (AccessTokenIDInner *)&id; + if (idInner->version != DEFAULT_TOKEN_VERSION || idInner->type != type) { + return RET_FAILED; + } + + Utils::UniqueWriteGuard idGuard(this->tokenIdLock_); + if (tokenIdSet_.count(id) != 0) { + return RET_FAILED; + } + + tokenIdSet_.insert(id); + return RET_SUCCESS; +} + +AccessTokenID AccessTokenIDManager::CreateTokenId(ATokenTypeEnum type) const +{ + unsigned int rand = GetRandomUint32(); + if (rand == 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, get random failed", __func__); + return 0; + } + + AccessTokenIDInner innerId = {0}; + innerId.version = DEFAULT_TOKEN_VERSION; + innerId.type = type; + innerId.res = 0; + innerId.tokenUniqueID = rand & TOKEN_RANDOM_MASK; + AccessTokenID tokenId = *(AccessTokenID *)&innerId; + return tokenId; +} + +AccessTokenID AccessTokenIDManager::CreateAndRegisterTokenId(ATokenTypeEnum type) +{ + AccessTokenID tokenId = 0; + // random maybe repeat, retry twice. + for (int i = 0; i < MAX_CREATE_TOKEN_ID_RETRY; i++) { + tokenId = CreateTokenId(type); + if (tokenId == 0) { + ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s called, create tokenId failed", __func__); + return 0; + } + + int ret = RegisterTokenId(tokenId, type); + if (ret == RET_SUCCESS) { + break; + } else if (i == MAX_CREATE_TOKEN_ID_RETRY - 1) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, reigster tokenId failed, maybe repeat, retry", __func__); + } else { + ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s called, reigster tokenId finally failed", __func__); + } + } + return tokenId; +} + +void AccessTokenIDManager::ReleaseTokenId(AccessTokenID id) +{ + Utils::UniqueWriteGuard idGuard(this->tokenIdLock_); + if (tokenIdSet_.count(id) == 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, id %{public}x is not exist", __func__, id); + return; + } + tokenIdSet_.erase(id); +} + +AccessTokenIDManager& AccessTokenIDManager::GetInstance() +{ + static AccessTokenIDManager instance; + return instance; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp b/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7577192279a6eb1f90342ae7c9e8d27330b7b388 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp @@ -0,0 +1,543 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_info_manager.h" + +#include "accesstoken_id_manager.h" +#include "accesstoken_log.h" +#include "data_storage.h" +#include "data_translator.h" +#include "data_validator.h" +#include "field_const.h" +#include "generic_values.h" +#include "hap_token_info_inner.h" +#include "permission_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenInfoManager"}; +} + +AccessTokenInfoManager::AccessTokenInfoManager() : hasInited_(false) +{} + +AccessTokenInfoManager::~AccessTokenInfoManager() +{ + if (!hasInited_) { + return; + } + this->tokenDataWorker_.Stop(); + this->hasInited_ = false; +} + +void AccessTokenInfoManager::Init() +{ + OHOS::Utils::UniqueWriteGuard lk(this->managerLock_); + if (hasInited_) { + return; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "init begin!"); + InitHapTokenInfos(); + InitNativeTokenInfos(); + this->tokenDataWorker_.Start(1); + hasInited_ = true; + ACCESSTOKEN_LOG_INFO(LABEL, "Init success"); +} + +void AccessTokenInfoManager::InitHapTokenInfos() +{ + std::vector hapTokenRes; + std::vector permDefRes; + std::vector permStateRes; + + DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_HAP_INFO, hapTokenRes); + DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_PERMISSION_DEF, permDefRes); + DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_PERMISSION_STATE, permStateRes); + + for (GenericValues& tokenValue : hapTokenRes) { + AccessTokenID tokenId = (AccessTokenID)tokenValue.GetInt(FIELD_TOKEN_ID); + int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(tokenId, TOKEN_HAP); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x add id failed.", + __func__, tokenId); + continue; + } + std::shared_ptr hap = std::make_shared(); + if (hap == nullptr) { + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x alloc failed.", __func__, tokenId); + continue; + } + ret = hap->RestoreHapTokenInfo(tokenId, tokenValue, permDefRes, permStateRes); + if (ret != RET_SUCCESS) { + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x restore failed.", __func__, tokenId); + continue; + } + + ret = AddHapTokenInfo(hap); + if (ret != RET_SUCCESS) { + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x add failed.", __func__, tokenId); + continue; + } + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s:restore hap token 0x%{public}x bundle name %{public}s user %{public}d inst %{public}d ok!", + __func__, tokenId, hap->GetBundleName().c_str(), hap->GetUserID(), hap->GetInstIndex()); + } +} + +void AccessTokenInfoManager::InitNativeTokenInfos() +{ + std::vector nativeTokenResults; + DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_NATIVE_INFO, nativeTokenResults); + for (GenericValues nativeTokenValue : nativeTokenResults) { + AccessTokenID tokenId = (AccessTokenID)nativeTokenValue.GetInt(FIELD_TOKEN_ID); + int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(tokenId, TOKEN_NATIVE); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x add failed.", __func__, tokenId); + continue; + } + std::shared_ptr native = std::make_shared(); + if (native == nullptr) { + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x alloc failed.", __func__, tokenId); + continue; + } + + ret = native->RestoreNativeTokenInfo(tokenId, nativeTokenValue); + if (ret != RET_SUCCESS) { + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x restore failed.", __func__, tokenId); + continue; + } + + ret = AddNativeTokenInfo(native); + if (ret != RET_SUCCESS) { + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x add failed.", __func__, tokenId); + continue; + } + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s:restore native token 0x%{public}x process name %{public}s ok!", + __func__, tokenId, native->GetProcessName().c_str()); + } +} + +std::string AccessTokenInfoManager::GetHapUniqueStr(const int& userID, + const std::string& bundleName, const int& instIndex) const +{ + return bundleName + "&" + std::to_string(userID) + "&" + std::to_string(instIndex); +} + +std::string AccessTokenInfoManager::GetHapUniqueStr(const std::shared_ptr& info) const +{ + if (info == nullptr) { + return std::string(""); + } + return GetHapUniqueStr(info->GetUserID(), info->GetBundleName(), info->GetInstIndex()); +} + +int AccessTokenInfoManager::AddHapTokenInfo(const std::shared_ptr& info) +{ + if (info == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: token info is null.", __func__); + return RET_FAILED; + } + AccessTokenID id = info->GetTokenID(); + + { + Utils::UniqueWriteGuard infoGuard(this->hapTokenInfoLock_); + if (hapTokenInfoMap_.count(id) > 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: token %{public}x info has exist.", __func__, id); + return RET_FAILED; + } + + std::string HapUniqueKey = GetHapUniqueStr(info); + if (hapTokenIdMap_.count(HapUniqueKey) > 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: token %{public}x Unique info has exist.", __func__, id); + return RET_FAILED; + } + + hapTokenInfoMap_[id] = info; + hapTokenIdMap_[HapUniqueKey] = id; + } + std::shared_ptr permPolicySet = info->GetHapInfoPermissionPolicySet(); + if (permPolicySet != nullptr) { + PermissionManager::GetInstance().AddDefPermissions(permPolicySet->permList_); + } + return RET_SUCCESS; +} + +int AccessTokenInfoManager::AddNativeTokenInfo(const std::shared_ptr& info) +{ + if (info == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: token info is null.", __func__); + return RET_FAILED; + } + + AccessTokenID id = info->GetTokenID(); + Utils::UniqueWriteGuard infoGuard(this->nativeTokenInfoLock_); + if (nativeTokenInfoMap_.count(id) > 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: token %{public}x has exist.", __func__, id); + return RET_FAILED; + } + nativeTokenInfoMap_[id] = info; + return RET_SUCCESS; +} + +std::shared_ptr AccessTokenInfoManager::GetHapTokenInfoInner(AccessTokenID id) +{ + Utils::UniqueReadGuard infoGuard(this->hapTokenInfoLock_); + if (hapTokenInfoMap_.count(id) == 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: token %{public}x is invalid.", __func__, id); + return nullptr; + } + return hapTokenInfoMap_[id]; +} + +int AccessTokenInfoManager::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& InfoParcel) +{ + std::shared_ptr infoPtr = GetHapTokenInfoInner(tokenID); + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: token %{public}x is invalid.", __func__, tokenID); + return RET_FAILED; + } + infoPtr->TranslateToHapTokenInfo(InfoParcel); + return RET_SUCCESS; +} + +std::shared_ptr AccessTokenInfoManager::GetHapPermissionPolicySet(AccessTokenID id) +{ + std::shared_ptr infoPtr = GetHapTokenInfoInner(id); + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: token %{public}x is invalid.", __func__, id); + return nullptr; + } + return infoPtr->GetHapInfoPermissionPolicySet(); +} + +std::shared_ptr AccessTokenInfoManager::GetNativeTokenInfoInner(AccessTokenID id) +{ + Utils::UniqueReadGuard infoGuard(this->nativeTokenInfoLock_); + if (nativeTokenInfoMap_.count(id) == 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: token %{public}x is invalid.", __func__, id); + return nullptr; + } + return nativeTokenInfoMap_[id]; +} + +int AccessTokenInfoManager::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& InfoParcel) +{ + std::shared_ptr infoPtr = GetNativeTokenInfoInner(tokenID); + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: token %{public}x is invalid.", __func__, tokenID); + return RET_FAILED; + } + + infoPtr->TranslateToNativeTokenInfo(InfoParcel); + return RET_SUCCESS; +} + +int AccessTokenInfoManager::RemoveTokenInfo(AccessTokenID id) +{ + ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(id); + if (type == TOKEN_HAP) { + // make sure that RemoveDefPermissions is called outside of the lock to avoid deadlocks. + PermissionManager::GetInstance().RemoveDefPermissions(id); + Utils::UniqueWriteGuard infoGuard(this->hapTokenInfoLock_); + if (hapTokenInfoMap_.count(id) == 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: hap token %{public}x is null.", __func__, id); + return RET_FAILED; + } + + const std::shared_ptr info = hapTokenInfoMap_[id]; + if (info == nullptr) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: hap token %{public}x is null.", __func__, id); + return RET_FAILED; + } + std::string HapUniqueKey = GetHapUniqueStr(info); + if (hapTokenIdMap_.count(HapUniqueKey) != 0) { + hapTokenIdMap_.erase(HapUniqueKey); + } + + hapTokenInfoMap_.erase(id); + } else if (type == TOKEN_NATIVE) { + Utils::UniqueWriteGuard infoGuard(this->nativeTokenInfoLock_); + if (nativeTokenInfoMap_.count(id) == 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: native token %{public}x is null.", __func__, id); + return RET_FAILED; + } + nativeTokenInfoMap_.erase(id); + } else { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: token %{public}x unknown type.", __func__, id); + return RET_FAILED; + } + + AccessTokenIDManager::GetInstance().ReleaseTokenId(id); + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s:remove hap token 0x%{public}x ok!", __func__, id); + RefreshTokenInfoIfNeeded(); + return RET_SUCCESS; +} + +int AccessTokenInfoManager::CreateHapTokenInfo( + const HapInfoParams& info, const HapPolicyParams& policy, AccessTokenIDEx& tokenIdEx) +{ + if (!DataValidator::IsUserIdValid(info.userID) || !DataValidator::IsBundleNameValid(info.bundleName) + || !DataValidator::IsAppIDDescValid(info.appIDDesc) || !DataValidator::IsDomainValid(policy.domain)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, hap token param failed", __func__); + return RET_FAILED; + } + + AccessTokenID tokenId = AccessTokenIDManager::GetInstance().CreateAndRegisterTokenId(TOKEN_HAP); + if (tokenId == 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, token Id create failed", __func__); + return RET_FAILED; + } + + std::shared_ptr tokenInfo = std::make_shared(); + if (tokenInfo == nullptr) { + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, alloc token info failed", __func__); + return RET_FAILED; + } + tokenInfo->Init(tokenId, info, policy); + + int ret = AddHapTokenInfo(tokenInfo); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s called, %{public}s add token info failed", + __func__, info.bundleName.c_str()); + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s:create hap token 0x%{public}x bundle name %{public}s user %{public}d inst %{public}d ok!", + __func__, tokenId, tokenInfo->GetBundleName().c_str(), tokenInfo->GetUserID(), tokenInfo->GetInstIndex()); + + tokenIdEx.tokenIdExStruct.tokenID = tokenId; + tokenIdEx.tokenIdExStruct.tokenAttr = 0; + RefreshTokenInfoIfNeeded(); + return RET_SUCCESS; +} + +int AccessTokenInfoManager::CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) +{ + std::shared_ptr infoPtr = GetNativeTokenInfoInner(tokenID); + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: token %{public}x is invalid.", __func__, tokenID); + return RET_FAILED; + } + + std::vector dcaps = infoPtr->GetDcap(); + for (auto iter = dcaps.begin(); iter != dcaps.end(); iter++) { + if (*iter == dcap) { + return RET_SUCCESS; + } + } + return RET_FAILED; +} + +AccessTokenID AccessTokenInfoManager::GetHapTokenID(int userID, const std::string& bundleName, int instIndex) +{ + Utils::UniqueReadGuard infoGuard(this->hapTokenInfoLock_); + std::string HapUniqueKey = GetHapUniqueStr(userID, bundleName, instIndex); + if (hapTokenIdMap_.count(HapUniqueKey) > 0) { + return hapTokenIdMap_[HapUniqueKey]; + } + return 0; +} + +AccessTokenID AccessTokenInfoManager::AllocLocalTokenID(const std::string& remoteDeviceID, + AccessTokenID remoteTokenID) +{ + return 0; +} + +bool AccessTokenInfoManager::TryUpdateExistNativeToken(const std::shared_ptr& infoPtr) +{ + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s called, info is null", __func__); + return false; + } + + Utils::UniqueWriteGuard infoGuard(this->nativeTokenInfoLock_); + AccessTokenID id = infoPtr->GetTokenID(); + // if native token is exist, update it + if (nativeTokenInfoMap_.count(id) == 0) { + return false; + } + std::shared_ptr oldTokenInfoPtr = nativeTokenInfoMap_[id]; + if (oldTokenInfoPtr != nullptr) { + nativeTokenInfoMap_[id] = infoPtr; + } else { + ACCESSTOKEN_LOG_ERROR( + LABEL, "%{public}s: native token exist, but is null.", __func__); + } + return true; +} + +int AccessTokenInfoManager::AllocNativeToken(const std::shared_ptr& infoPtr) +{ + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s called, token info is null", __func__); + return RET_FAILED; + } + + AccessTokenID id = infoPtr->GetTokenID(); + int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(id, TOKEN_NATIVE); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, token Id register fail", __func__); + return RET_FAILED; + } + + ret = AddNativeTokenInfo(infoPtr); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, %{public}s add token info failed", + __func__, infoPtr->GetProcessName().c_str()); + AccessTokenIDManager::GetInstance().ReleaseTokenId(id); + return RET_FAILED; + } + + return RET_SUCCESS; +} + +void AccessTokenInfoManager::ProcessNativeTokenInfos( + const std::vector>& tokenInfos) +{ + for (auto& infoPtr: tokenInfos) { + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s called, token info from libat is null", __func__); + continue; + } + bool isUpdated = TryUpdateExistNativeToken(infoPtr); + if (!isUpdated) { + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s: token 0x%{public}x process name %{public}s is new, add to manager!", + __func__, infoPtr->GetTokenID(), infoPtr->GetProcessName().c_str()); + int ret = AllocNativeToken(infoPtr); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "%{public}s: token 0x%{public}x process name %{public}s add to manager failed!", + __func__, infoPtr->GetTokenID(), infoPtr->GetProcessName().c_str()); + } + } + } + RefreshTokenInfoIfNeeded(); +} + +int AccessTokenInfoManager::UpdateHapToken(AccessTokenID tokenID, + const std::string& appIDDesc, const HapPolicyParams& policy) +{ + std::shared_ptr infoPtr = GetHapTokenInfoInner(tokenID); + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s:token 0x%{public}x is null, can not update!", __func__, tokenID); + return RET_FAILED; + } + + Utils::UniqueWriteGuard infoGuard(this->hapTokenInfoLock_); + infoPtr->Update(appIDDesc, policy); + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s: token 0x%{public}x bundle name %{public}s user %{public}d inst %{public}d update ok!", + __func__, tokenID, infoPtr->GetBundleName().c_str(), infoPtr->GetUserID(), infoPtr->GetInstIndex()); + + RefreshTokenInfoIfNeeded(); + return RET_SUCCESS; +} + +AccessTokenInfoManager& AccessTokenInfoManager::GetInstance() +{ + static AccessTokenInfoManager instance; + return instance; +} + +void AccessTokenInfoManager::StoreAllTokenInfo() +{ + std::vector hapInfoValues; + std::vector permDefValues; + std::vector permStateValues; + std::vector nativeTokenValues; + { + Utils::UniqueReadGuard infoGuard(this->hapTokenInfoLock_); + for (auto iter = hapTokenInfoMap_.begin(); iter != hapTokenInfoMap_.end(); iter++) { + if (iter->second != nullptr) { + iter->second->StoreHapInfo(hapInfoValues, permDefValues, permStateValues); + } + } + } + + { + Utils::UniqueReadGuard infoGuard(this->nativeTokenInfoLock_); + for (auto iter = nativeTokenInfoMap_.begin(); iter != nativeTokenInfoMap_.end(); iter++) { + if (iter->second != nullptr) { + iter->second->StoreNativeInfo(nativeTokenValues); + } + } + } + + DataStorage::GetRealDataStorage().RefreshAll(DataStorage::ACCESSTOKEN_HAP_INFO, hapInfoValues); + DataStorage::GetRealDataStorage().RefreshAll(DataStorage::ACCESSTOKEN_NATIVE_INFO, nativeTokenValues); + DataStorage::GetRealDataStorage().RefreshAll(DataStorage::ACCESSTOKEN_PERMISSION_DEF, permDefValues); + DataStorage::GetRealDataStorage().RefreshAll(DataStorage::ACCESSTOKEN_PERMISSION_STATE, permStateValues); +} + +void AccessTokenInfoManager::RefreshTokenInfoIfNeeded() +{ + if (tokenDataWorker_.GetCurTaskNum() > 1) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s: has refresh task!", __func__); + return; + } + tokenDataWorker_.AddTask([]() { + AccessTokenInfoManager::GetInstance().StoreAllTokenInfo(); + + // Sleep for one second to avoid frequent refresh of the database. + std::this_thread::sleep_for(std::chrono::seconds(1)); + }); +} + +void AccessTokenInfoManager::Dump(std::string& dumpInfo) +{ + Utils::UniqueReadGuard hapInfoGuard(this->hapTokenInfoLock_); + for (auto iter = hapTokenInfoMap_.begin(); iter != hapTokenInfoMap_.end(); iter++) { + if (iter->second != nullptr) { + iter->second->ToString(dumpInfo); + } + } + + Utils::UniqueReadGuard nativeInfoGuard(this->nativeTokenInfoLock_); + for (auto iter = nativeTokenInfoMap_.begin(); iter != nativeTokenInfoMap_.end(); iter++) { + if (iter->second != nullptr) { + iter->second->ToString(dumpInfo); + } + } +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp b/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0d71b74463af31649c5c629f98afed14a97fdf7f --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hap_token_info_inner.h" + +#include "accesstoken_id_manager.h" +#include "accesstoken_log.h" +#include "data_translator.h" +#include "data_validator.h" +#include "field_const.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "HapTokenInfoInner"}; +} +void HapTokenInfoInner::Init(AccessTokenID id, const HapInfoParams &info, const HapPolicyParams &policy) +{ + tokenID_ = id; + userID_ = info.userID; + bundleName_ = info.bundleName; + instIndex_ = info.instIndex; + appID_ = info.appIDDesc; + deviceID_ = "0"; + apl_ = policy.apl; + permPolicySet_ = PermissionPolicySet::BuildPermissionPolicySet(id, policy.permList, policy.permStateList); +} + +void HapTokenInfoInner::Update(const std::string& appIDDesc, const HapPolicyParams& policy) +{ + appID_ = appIDDesc; + if (permPolicySet_ == nullptr) { + permPolicySet_ = PermissionPolicySet::BuildPermissionPolicySet(tokenID_, + policy.permList, policy.permStateList); + return; + } + + permPolicySet_->Update(policy.permList, policy.permStateList); + return; +} + +void HapTokenInfoInner::TranslateToHapTokenInfo(HapTokenInfo& InfoParcel) const +{ + InfoParcel.apl = apl_; + InfoParcel.ver = ver_; + InfoParcel.userID = userID_; + InfoParcel.bundleName = bundleName_; + InfoParcel.instIndex = instIndex_; + InfoParcel.appID = appID_; + InfoParcel.deviceID = deviceID_; + InfoParcel.tokenID = tokenID_; + InfoParcel.tokenAttr = tokenAttr_; +} + +void HapTokenInfoInner::TranslationIntoGenericValues(GenericValues& outGenericValues) const +{ + outGenericValues.Put(FIELD_TOKEN_ID, tokenID_); + outGenericValues.Put(FIELD_USER_ID, userID_); + outGenericValues.Put(FIELD_BUNDLE_NAME, bundleName_); + outGenericValues.Put(FIELD_INST_INDEX, instIndex_); + outGenericValues.Put(FIELD_APP_ID, appID_); + outGenericValues.Put(FIELD_DEVICE_ID, deviceID_); + outGenericValues.Put(FIELD_APL, apl_); + outGenericValues.Put(FIELD_TOKEN_VERSION, ver_); + outGenericValues.Put(FIELD_TOKEN_ATTR, tokenAttr_); +} + +int HapTokenInfoInner::RestoreHapTokenBasicInfo(const GenericValues& inGenericValues) +{ + userID_ = inGenericValues.GetInt(FIELD_USER_ID); + bundleName_ = inGenericValues.GetString(FIELD_BUNDLE_NAME); + instIndex_ = inGenericValues.GetInt(FIELD_INST_INDEX); + appID_ = inGenericValues.GetString(FIELD_APP_ID); + deviceID_ = inGenericValues.GetString(FIELD_DEVICE_ID); + int aplNum = inGenericValues.GetInt(FIELD_APL); + if (DataValidator::IsAplNumValid(aplNum)) { + apl_ = (ATokenAplEnum)aplNum; + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, + "%{public}s called, tokenID: 0x%{public}x apl is error, value %{public}d", __func__, tokenID_, aplNum); + return RET_FAILED; + } + ver_ = inGenericValues.GetInt(FIELD_TOKEN_VERSION); + if (ver_ != DEFAULT_TOKEN_VERSION) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "%{public}s called, tokenID: 0x%{public}x version is error, version %{public}d", __func__, tokenID_, ver_); + return RET_FAILED; + } + tokenAttr_ = inGenericValues.GetInt(FIELD_TOKEN_ATTR); + return RET_SUCCESS; +} + +int HapTokenInfoInner::RestoreHapTokenInfo(AccessTokenID tokenId, + GenericValues& tokenValue, const std::vector& permDefRes, + const std::vector& permStateRes) +{ + tokenID_ = tokenId; + int ret = RestoreHapTokenBasicInfo(tokenValue); + if (ret != RET_SUCCESS) { + return RET_FAILED; + } + permPolicySet_ = PermissionPolicySet::RestorePermissionPolicy(tokenId, + permDefRes, permStateRes); + return RET_SUCCESS; +} + +void HapTokenInfoInner::StoreHapBasicInfo(std::vector& valueList) const +{ + GenericValues genericValues; + TranslationIntoGenericValues(genericValues); + valueList.emplace_back(genericValues); +} + +void HapTokenInfoInner::StoreHapInfo(std::vector& hapInfoValues, + std::vector& permDefValues, + std::vector& permStateValues) const +{ + StoreHapBasicInfo(hapInfoValues); + if (permPolicySet_ != nullptr) { + permPolicySet_->StorePermissionPolicySet(permDefValues, permStateValues); + } +} + +std::shared_ptr HapTokenInfoInner::GetHapInfoPermissionPolicySet() const +{ + return permPolicySet_; +} + +int HapTokenInfoInner::GetUserID() const +{ + return userID_; +} + +std::string HapTokenInfoInner::GetBundleName() const +{ + return bundleName_; +} + +int HapTokenInfoInner::GetInstIndex() const +{ + return instIndex_; +} + +AccessTokenID HapTokenInfoInner::GetTokenID() const +{ + return tokenID_; +} + +void HapTokenInfoInner::ToString(std::string& info) const +{ + info.append(R"({"tokenID": )" + std::to_string(tokenID_)); + info.append(R"(, "tokenAttr": )" + std::to_string(tokenAttr_)); + info.append(R"(, "ver": )" + std::to_string(ver_)); + info.append(R"(, "userId": )" + std::to_string(userID_)); + info.append(R"(, "bundleName": ")" + bundleName_ + R"(")"); + info.append(R"(, "instIndex": )" + std::to_string(instIndex_)); + info.append(R"(, "appID": ")" + appID_ + R"(")"); + info.append(R"(, "deviceID": ")" + deviceID_ + R"(")"); + info.append(R"(, "apl": )" + std::to_string(apl_)); + + if (permPolicySet_ != nullptr) { + permPolicySet_->ToString(info); + } + info.append("}"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp b/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e57208456f75bf35ac94d118ea07489166ca6c5f --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_token_info_inner.h" + +#include "data_translator.h" +#include "data_validator.h" +#include "field_const.h" +#include "nlohmann/json.hpp" + +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "NativeTokenInfoInner"}; +} + +void NativeTokenInfoInner::Init(AccessTokenID id, const std::string& processName, + ATokenAplEnum apl, const std::vector& dcap) +{ + tokenID_ = id; + processName_ = processName; + apl_ = apl; + dcap_ = dcap; +} + +std::string NativeTokenInfoInner::DcapToString(const std::vector& dcap) const +{ + std::string dcapStr; + for (auto iter = dcap.begin(); iter != dcap.end(); iter++) { + dcapStr.append(*iter); + if (iter != (dcap.end() - 1)) { + dcapStr.append(","); + } + } + return dcapStr; +} + +int NativeTokenInfoInner::TranslationIntoGenericValues(GenericValues& outGenericValues) const +{ + outGenericValues.Put(FIELD_TOKEN_ID, tokenID_); + outGenericValues.Put(FIELD_PROCESS_NAME, processName_); + outGenericValues.Put(FIELD_APL, apl_); + outGenericValues.Put(FIELD_TOKEN_VERSION, ver_); + outGenericValues.Put(FIELD_DCAP, DcapToString(dcap_)); + outGenericValues.Put(FIELD_TOKEN_ATTR, tokenAttr_); + + return RET_SUCCESS; +} + +int NativeTokenInfoInner::RestoreNativeTokenInfo(AccessTokenID tokenId, const GenericValues& inGenericValues) +{ + tokenID_ = tokenId; + processName_ = inGenericValues.GetString(FIELD_PROCESS_NAME); + int aplNum = inGenericValues.GetInt(FIELD_APL); + if (DataValidator::IsAplNumValid(aplNum)) { + apl_ = (ATokenAplEnum)aplNum; + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, + "%{public}s called, tokenID: 0x%{public}x apl is error, value %{public}d", __func__, tokenID_, aplNum); + return RET_FAILED; + } + ver_ = inGenericValues.GetInt(FIELD_TOKEN_VERSION); + if (ver_ != DEFAULT_TOKEN_VERSION) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "%{public}s called, tokenID: 0x%{public}x version is error, version %{public}d", __func__, tokenID_, ver_); + return RET_FAILED; + } + + SetDcaps(inGenericValues.GetString(FIELD_DCAP)); + tokenAttr_ = inGenericValues.GetInt(FIELD_TOKEN_ATTR); + return RET_SUCCESS; +} + +void NativeTokenInfoInner::TranslateToNativeTokenInfo(NativeTokenInfo& InfoParcel) const +{ + InfoParcel.apl = apl_; + InfoParcel.ver = ver_; + InfoParcel.processName = processName_; + InfoParcel.dcap = dcap_; + InfoParcel.tokenID = tokenID_; + InfoParcel.tokenAttr = tokenAttr_; +} + +void NativeTokenInfoInner::StoreNativeInfo(std::vector& valueList) const +{ + GenericValues genericValues; + TranslationIntoGenericValues(genericValues); + valueList.emplace_back(genericValues); +} + +bool NativeTokenInfoInner::FromJsonString(const std::string& jsonString) +{ + nlohmann::json jsonObject = nlohmann::json::parse(jsonString); + if (jsonObject.is_discarded()) { + return false; + } + + if (jsonObject.find(JSON_PROCESS_NAME) != jsonObject.end()) { + processName_ = jsonObject.at(JSON_PROCESS_NAME).get(); + } + + if (jsonObject.find(JSON_APL) != jsonObject.end()) { + int aplNum = jsonObject.at(JSON_APL).get(); + if (DataValidator::IsAplNumValid(aplNum)) { + apl_ = (ATokenAplEnum)aplNum; + } + } + + if (jsonObject.find(JSON_VERSION) != jsonObject.end()) { + ver_ = jsonObject.at(JSON_VERSION).get(); + } + + if (jsonObject.find(JSON_TOKEN_ID) != jsonObject.end()) { + tokenID_ = jsonObject.at(JSON_TOKEN_ID).get(); + } + + if (jsonObject.find(JSON_TOKEN_ATTR) != jsonObject.end()) { + tokenAttr_ = jsonObject.at(JSON_TOKEN_ATTR).get(); + } + + if (jsonObject.find(JSON_DCAPS) != jsonObject.end()) { + dcap_ = jsonObject.at(JSON_DCAPS).get>(); + } + + return true; +} + +AccessTokenID NativeTokenInfoInner::GetTokenID() const +{ + return tokenID_; +} + +std::vector NativeTokenInfoInner::GetDcap() const +{ + return dcap_; +} + +std::string NativeTokenInfoInner::GetProcessName() const +{ + return processName_; +} + +void NativeTokenInfoInner::SetDcaps(const std::string& dcapStr) +{ + int start = 0; + while (true) { + unsigned int offset = dcapStr.find(',', start); + if (offset == std::string::npos) { + dcap_.push_back(dcapStr.substr(start)); + break; + } + dcap_.push_back(dcapStr.substr(start, offset)); + start = offset + 1; + } +} + +void NativeTokenInfoInner::ToString(std::string& info) const +{ + info.append(R"({"tokenID": )" + std::to_string(tokenID_)); + info.append(R"(, "tokenAttr": )" + std::to_string(tokenAttr_)); + info.append(R"(, "ver": )" + std::to_string(ver_)); + info.append(R"(, "processName": ")" + processName_ + R"(")"); + info.append(R"(, "apl": )" + std::to_string(apl_)); + info.append(R"(, "dcap": ")" + DcapToString(dcap_) + R"(")"); + info.append("}"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/accesstokenmanager/main/sa_profile/3503.xml b/services/accesstokenmanager/main/sa_profile/3503.xml new file mode 100644 index 0000000000000000000000000000000000000000..d20563c4603417e3bc8da37829532ecf5be110d3 --- /dev/null +++ b/services/accesstokenmanager/main/sa_profile/3503.xml @@ -0,0 +1,24 @@ + + + + accesstoken_service + + 3503 + libaccesstoken_manager_service.z.so + true + false + 1 + + diff --git a/services/accesstokenmanager/main/sa_profile/BUILD.gn b/services/accesstokenmanager/main/sa_profile/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c199a410c692bb3ecc713336c8f02718acf3731f --- /dev/null +++ b/services/accesstokenmanager/main/sa_profile/BUILD.gn @@ -0,0 +1,20 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos/sa_profile/sa_profile.gni") + +ohos_sa_profile("accesstoken_sa_profile_standard") { + part_name = "access_token" + + sources = [ "3503.xml" ] +} diff --git a/services/accesstokenmanager/test/BUILD.gn b/services/accesstokenmanager/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..b22343c7f45be05b674e7e99a8ec8cd00f37916c --- /dev/null +++ b/services/accesstokenmanager/test/BUILD.gn @@ -0,0 +1,53 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +ohos_unittest("libaccesstoken_manager_service_standard_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "//utils/native/base/include", + "//third_party/googletest/include", + "//base/security/access_token/services/accesstokenmanager/main/cpp/include/service", + "//base/security/access_token/services/accesstokenmanager/main/cpp/include/token", + "//base/security/access_token/services/accesstokenmanager/main/cpp/include/permission", + "//base/security/access_token/services/accesstokenmanager/main/cpp/include/database", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/frameworks/accesstoken/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/main/cpp/include", + ] + + sources = [ + "unittest/cpp/src/accesstoken_info_manager_test.cpp", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "//base/security/access_token/services/accesstokenmanager/:accesstoken_manager_service", + "//base/security/access_token/frameworks/common:accesstoken_common_cxx", + "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + deps = [ ":libaccesstoken_manager_service_standard_test" ] +} diff --git a/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.cpp b/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89bec7c8883596fc8022cf2610777436a359bf76 --- /dev/null +++ b/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.cpp @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_info_manager_test.h" + +#include +#include +#include "accesstoken_info_manager.h" +#include "accesstoken_log.h" + +using namespace testing::ext; +using namespace OHOS::Security::AccessToken; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenInfoManagerTest" +}; + +static PermissionDef g_infoManagerTestPermDef1 = { + .permissionName = "open the door", + .bundleName = "accesstoken_test", + .grantMode = 1, + .label = "label", + .labelId = 1, + .description = "open the door", + .descriptionId = 1, + .availableScope = 1 +}; + +static PermissionDef g_infoManagerTestPermDef2 = { + .permissionName = "break the door", + .bundleName = "accesstoken_test", + .grantMode = 1, + .label = "label", + .labelId = 1, + .description = "break the door", + .descriptionId = 1, + .availableScope = 1 +}; + +static PermissionStateFull g_infoManagerTestState1 = { + .grantFlags = {1}, + .grantStatus = {1}, + .isGeneral = true, + .permissionName = "open the door", + .resDeviceID = {"local"} +}; + +static PermissionStateFull g_infoManagerTestState2 = { + .permissionName = "break the door", + .isGeneral = false, + .grantFlags = {1, 2}, + .grantStatus = {1, 3}, + .resDeviceID = {"device 1", "device 2"} +}; + +static HapInfoParams g_infoManagerTestInfoParms = { + .bundleName = "accesstoken_test", + .userID = 1, + .instIndex = 0, + .appIDDesc = "testtesttesttest" +}; + +static HapPolicyParams g_infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {g_infoManagerTestPermDef1, g_infoManagerTestPermDef2}, + .permStateList = {g_infoManagerTestState1, g_infoManagerTestState2} +}; +} + +void AccessTokenInfoManagerTest::SetUpTestCase() +{} + +void AccessTokenInfoManagerTest::TearDownTestCase() +{} + +void AccessTokenInfoManagerTest::SetUp() +{} + +void AccessTokenInfoManagerTest::TearDown() +{} + +HWTEST_F(AccessTokenInfoManagerTest, Init001, TestSize.Level1) +{ + AccessTokenInfoManager::GetInstance().Init(); + std::string dumpInfo; + AccessTokenInfoManager::GetInstance().Dump(dumpInfo); + GTEST_LOG_(INFO) << "dump all:" << dumpInfo.c_str(); + + // delete test token + AccessTokenID getTokenId = AccessTokenInfoManager::GetInstance().GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, g_infoManagerTestInfoParms.instIndex); + + if (getTokenId != 0) { + int ret = AccessTokenInfoManager::GetInstance().RemoveTokenInfo(getTokenId); + ASSERT_EQ(RET_SUCCESS, ret); + } + + ASSERT_EQ(RET_SUCCESS, RET_SUCCESS); +} + +/** + * @tc.name: CreateHapTokenInfo001 + * @tc.desc: Verify the CreateHapTokenInfo add one hap token function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(AccessTokenInfoManagerTest, CreateHapTokenInfo001, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo(g_infoManagerTestInfoParms, + g_infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + std::shared_ptr tokenInfo; + tokenInfo = AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_NE(nullptr, tokenInfo); + std::string infoDes; + tokenInfo->ToString(infoDes); + GTEST_LOG_(INFO) << "get hap token info:" << infoDes.c_str(); + + ret = AccessTokenInfoManager::GetInstance().RemoveTokenInfo(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; + + tokenInfo = AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(nullptr, tokenInfo); +} + +/** + * @tc.name: CreateHapTokenInfo002 + * @tc.desc: Verify the CreateHapTokenInfo add one hap token twice function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(AccessTokenInfoManagerTest, CreateHapTokenInfo002, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "AddHapToken001 fill data"); + + AccessTokenIDEx tokenIdEx = {0}; + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo(g_infoManagerTestInfoParms, + g_infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + AccessTokenIDEx tokenIdEx1 = {0}; + ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo(g_infoManagerTestInfoParms, + g_infoManagerTestPolicyPrams, tokenIdEx1); + ASSERT_EQ(RET_FAILED, ret); + ASSERT_EQ(0, tokenIdEx1.tokenIdExStruct.tokenID); + GTEST_LOG_(INFO) << "add same hap token"; + + std::shared_ptr tokenInfo; + tokenInfo = AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_NE(nullptr, tokenInfo); + + std::string infoDes; + tokenInfo->ToString(infoDes); + GTEST_LOG_(INFO) << "get hap token info:" << infoDes.c_str(); + + ret = AccessTokenInfoManager::GetInstance().RemoveTokenInfo(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; +} + +/** + * @tc.name: GetHapTokenID001 + * @tc.desc: Verify the GetHapTokenID by userID/bundleName/instIndex, function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(AccessTokenInfoManagerTest, GetHapTokenID001, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo(g_infoManagerTestInfoParms, + g_infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + AccessTokenID getTokenId = AccessTokenInfoManager::GetInstance().GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, g_infoManagerTestInfoParms.instIndex); + ASSERT_EQ(tokenIdEx.tokenIdExStruct.tokenID, getTokenId); + GTEST_LOG_(INFO) << "find hap info"; + + std::shared_ptr tokenInfo; + tokenInfo = AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_NE(nullptr, tokenInfo); + GTEST_LOG_(INFO) << "remove the token info"; + + ret = AccessTokenInfoManager::GetInstance().RemoveTokenInfo(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; +} + +/** + * @tc.name: UpdateHapToken001 + * @tc.desc: Verify the UpdateHapToken token function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(AccessTokenInfoManagerTest, UpdateHapToken001, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo(g_infoManagerTestInfoParms, + g_infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + HapPolicyParams policy = g_infoManagerTestPolicyPrams; + policy.apl = APL_SYSTEM_BASIC; + ret = AccessTokenInfoManager::GetInstance().UpdateHapToken(tokenIdEx.tokenIdExStruct.tokenID, + std::string("updateAppId"), policy); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "update the hap token"; + + std::shared_ptr tokenInfo; + tokenInfo = AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_NE(nullptr, tokenInfo); + std::string infoDes; + tokenInfo->ToString(infoDes); + GTEST_LOG_(INFO) << "get hap token info:" << infoDes.c_str(); + + ret = AccessTokenInfoManager::GetInstance().RemoveTokenInfo(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; +} diff --git a/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.h b/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.h new file mode 100644 index 0000000000000000000000000000000000000000..3d92f465012463b0cae197e70846727999270286 --- /dev/null +++ b/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_INFO_MANAGER_TEST_H +#define ACCESSTOKEN_INFO_MANAGER_TEST_H + +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class AccessTokenInfoManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_INFO_MANAGER_TEST_H diff --git a/services/tokensyncmanager/BUILD.gn b/services/tokensyncmanager/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..375cba960347116c2bb0b77e8c58b4ff62adc9a7 --- /dev/null +++ b/services/tokensyncmanager/BUILD.gn @@ -0,0 +1,48 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_shared_library("tokensync_manager_service") { + subsystem_name = "security" + part_name = "access_token" + + include_dirs = [ + "include", + "//utils/system/safwk/native/include", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/frameworks/tokensync/include", + #"//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include/permission", + ] + + sources = [ + "main/cpp/tokensync_manager_service.cpp", + "main/cpp/tokensync_manager_stub.cpp", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + #"//base/security/accesstoken/frameworks/accesstooken/permissioncommunicationadapter:permission_standard_communication_adapter_cxx", + #"//base/security/accesstoken/frameworks/accesstooken/common:permission_standard_infrastructure_cxx", + #"//third_party/sqlite:sqlite", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] +} diff --git a/services/tokensyncmanager/main/cpp/tokensync_manager_service.cpp b/services/tokensyncmanager/main/cpp/tokensync_manager_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6e011816a5aa090fcfa644ff4762e87984da78ab --- /dev/null +++ b/services/tokensyncmanager/main/cpp/tokensync_manager_service.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "tokensync_manager_service.h" + +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace TokenSync { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncManagerService"}; +} + +const bool REGISTER_RESULT = + SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); + +TokenSyncManagerService::TokenSyncManagerService() + : SystemAbility(SA_ID_TOKENSYNC_MANAGER_SERVICE, true), state_(ServiceRunningState::STATE_NOT_START) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "TokenSyncManagerService()"); +} + +TokenSyncManagerService::~TokenSyncManagerService() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "~TokenSyncManagerService()"); +} + +void TokenSyncManagerService::OnStart() +{ + if (state_ == ServiceRunningState::STATE_RUNNING) { + ACCESSTOKEN_LOG_INFO(LABEL, "TokenSyncManagerService has already started!"); + return; + } + ACCESSTOKEN_LOG_INFO(LABEL, "TokenSyncManagerService is starting"); + state_ = ServiceRunningState::STATE_RUNNING; + bool ret = Publish(DelayedSingleton::GetInstance().get()); + if (!ret) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to publish service!"); + return; + } + ACCESSTOKEN_LOG_INFO(LABEL, "Congratulations, TokenSyncManagerService start successfully!"); +} + +void TokenSyncManagerService::OnStop() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "stop service"); + state_ = ServiceRunningState::STATE_NOT_START; +} + +int TokenSyncManagerService::VerifyPermission( + const std::string& bundleName, const std::string& permissionName, int userId) +{ + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s called, packageName: %{public}s, permissionName: %{public}s, userId: %{public}d", __func__, + bundleName.c_str(), permissionName.c_str(), userId); + return 0; +} + +bool TokenSyncManagerService::Initialize() const +{ + return true; +} +} // namespace TokenSync +} // namespace Security +} diff --git a/services/tokensyncmanager/main/cpp/tokensync_manager_service.h b/services/tokensyncmanager/main/cpp/tokensync_manager_service.h new file mode 100644 index 0000000000000000000000000000000000000000..0766099945a835ad7765846d002c198641b5eed6 --- /dev/null +++ b/services/tokensyncmanager/main/cpp/tokensync_manager_service.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKENSYNC_MANAGER_SERVICE_H +#define TOKENSYNC_MANAGER_SERVICE_H + +#include + +#include "iremote_object.h" +#include "nocopyable.h" +#include "singleton.h" +#include "system_ability.h" +#include "tokensync_manager_stub.h" + +namespace OHOS { +namespace Security { +namespace TokenSync { +enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; +class TokenSyncManagerService final : public SystemAbility, public TokenSyncManagerStub { + DECLARE_DELAYED_SINGLETON(TokenSyncManagerService); + DECLEAR_SYSTEM_ABILITY(TokenSyncManagerService); + +public: + void OnStart() override; + void OnStop() override; + + int VerifyPermission(const std::string& bundleName, const std::string& permissionName, int userId) override; + +private: + bool Initialize() const; + + ServiceRunningState state_; +}; +} // namespace TokenSync +} // namespace Security +} // namespace OHOS +#endif // TOKENSYNC_MANAGER_SERVICE_H diff --git a/services/tokensyncmanager/main/cpp/tokensync_manager_stub.cpp b/services/tokensyncmanager/main/cpp/tokensync_manager_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..21c222bd6dc68b276530775fc83d0d89a468961a --- /dev/null +++ b/services/tokensyncmanager/main/cpp/tokensync_manager_stub.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "tokensync_manager_stub.h" + +#include "accesstoken_log.h" + +#include "ipc_skeleton.h" +#include "string_ex.h" + +namespace OHOS { +namespace Security { +namespace TokenSync { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncManagerStub"}; +} + +int32_t TokenSyncManagerStub::OnRemoteRequest( + uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, code: %{public}d", __func__, code); + std::u16string descriptor = data.ReadInterfaceToken(); + if (descriptor != ITokenSyncManager::GetDescriptor()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "get unexpect descriptor: %{public}s", Str16ToStr8(descriptor).c_str()); + return -1; + } + switch (code) { + case static_cast(ITokenSyncManager::InterfaceCode::VERIFY_PERMISSION): + VerifyPermissionInner(data, reply); + break; + default: + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + return NO_ERROR; +} + +void TokenSyncManagerStub::VerifyPermissionInner(MessageParcel& data, MessageParcel& reply) +{ + std::string bundleName = data.ReadString(); + std::string permissionName = data.ReadString(); + int userId = data.ReadInt32(); + int result = this->VerifyPermission(bundleName, permissionName, userId); + reply.WriteInt32(result); +} +} // namespace TokenSync +} // namespace Security +} // namespace OHOS diff --git a/services/tokensyncmanager/main/cpp/tokensync_manager_stub.h b/services/tokensyncmanager/main/cpp/tokensync_manager_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..991e3947f40eec54bdb354de6e1273191dd3e3ee --- /dev/null +++ b/services/tokensyncmanager/main/cpp/tokensync_manager_stub.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKENSYNC_MANAGER_STUB_H +#define TOKENSYNC_MANAGER_STUB_H + +#include "i_tokensync_manager.h" + +#include "iremote_stub.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace TokenSync { +class TokenSyncManagerStub : public IRemoteStub { +public: + TokenSyncManagerStub() = default; + virtual ~TokenSyncManagerStub() = default; + + int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& options) override; + +private: + void VerifyPermissionInner(MessageParcel& data, MessageParcel& reply); +}; +} // namespace TokenSync +} // namespace Security +} // namespace OHOS +#endif // TOKENSYNC_MANAGER_STUB_H diff --git a/services/tokensyncmanager/main/sa_profile/3504.xml b/services/tokensyncmanager/main/sa_profile/3504.xml new file mode 100644 index 0000000000000000000000000000000000000000..3348d7156246c501b33e3d0124b586556b618cb0 --- /dev/null +++ b/services/tokensyncmanager/main/sa_profile/3504.xml @@ -0,0 +1,24 @@ + + + + foundation + + 3504 + libtoken_manager_service.z.so + true + true + 1 + + diff --git a/services/tokensyncmanager/main/sa_profile/BUILD.gn b/services/tokensyncmanager/main/sa_profile/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..40f038f5a9c80e6ef23182ef0fe5020b7ef65437 --- /dev/null +++ b/services/tokensyncmanager/main/sa_profile/BUILD.gn @@ -0,0 +1,22 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos/sa_profile/sa_profile.gni") + +ohos_sa_profile("tokensync_sa_profile_standard") { + part_name = "token_sync" + + sources = [ "3504.xml" ] +} + +