Auditing is generated inside the API Server and records requests to the Kubernetes API along with the results of those requests. ACK clusters provide API Server audit logs, which help cluster administrators identify who performed which operation on which resource and at what time. Audit logs let you trace the operation history of a cluster and troubleshoot cluster failures, which reduces the security O&M burden of the cluster.
Usage notes
This topic applies only to ACK managed cluster, ACK dedicated cluster, and ACK Serverless cluster.
To use the cluster API Server auditing feature in a registered cluster, see Enable the cluster API Server auditing feature.
Billing
You can view billing details, including the fees of audit logs, on the Bills overview page of Expenses and Bills. For instructions, see Query costs and bills. For information about the billing method of audit logs, see Billing by feature.
Step 1: Enable the cluster API Server auditing feature
When you create a Kubernetes cluster, Enable Log Service is selected by default, which enables the cluster API Server auditing feature. If you have not enabled the feature, follow the steps below to enable it.
-
Log on to the ACK console. In the left navigation pane, click Clusters.
-
On the Clusters page, click the name of your cluster. In the left navigation pane, click .
On the Audit page, click the Cluster Auditing tab.
If you have not enabled cluster logging or cluster auditing, manually select a Simple Log Service (SLS) Project and enable the feature as prompted on the page.
Make sure that the Simple Log Service (SLS) resources in your account do not exceed the quota. Otherwise, the cluster auditing feature fails to be enabled.
The quota on the number of log Projects that can be created.
The quota on the number of Logstores that can be created in a single log Project.
The quota on the number of dashboards that can be created in a single log Project.
For information about SLS quotas and how to adjust them, see Adjust resource quotas.
Step 2: View audit reports
Do not modify the audit reports. If you need a custom audit report, create a new report in the Simple Log Service console.
ACK clusters have four built-in audit log reports: Audit Center Overview, Resource Operation Overview, Resource Operation Details List, and Kubernetes CVE Security Risks. On the Cluster Auditing page, you can select the filter dimensions of audit events, such as namespace and Resource Access Management (RAM) user, and get the following information from the reports.
After you get the results, you can also click the icon
in the upper-right corner of the target area for more operations, such as viewing a specified area in full screen and previewing the query statement of a pinned area.
Audit Center Overview
Audit Center Overview displays an overall view of the events in an ACK cluster and the details of important events, such as RAM user operations, public network access, command execution, resource deletion, access to secrets, and Kubernetes CVE security risks.
Resource Operation Overview
Resource Operation Overview displays operation statistics for common compute resources, network resources, and storage resources in a Kubernetes cluster. Operations include create, update, delete, and access. The resources are categorized as follows:
Compute resources: Deployment, StatefulSet, CronJob, DaemonSet, Job, and Pod.
Network resources: Service and Ingress.
Storage resources: ConfigMap, Secret, and PersistentVolumeClaim.
Access control resources: Role, ClusterRole, RoleBinding, and ClusterRoleBinding
On the Resource Operation Overview tab, you can filter data by using the time range selector at the top, such as 1 Week Relative, and the Namespace drop-down list. The page is grouped by resource type, and the create, delete, access, and update operations of each resource type are displayed as statistics in a separate donut chart panel. The tabs at the same level also include Audit Center Overview, Resource Operation Details List, and Kubernetes CVE Security Risks.
Resource Operation Details List
This report displays the detailed operation list of a specific type of resource in a Kubernetes cluster. You must select or enter a specific resource type to run a real-time query. The report displays the total number of events of each type for resource operations, the Namespace distribution, the success rate, the time-series trend, and the detailed operation list.
To view CustomResourceDefinition (CRD) resources registered in Kubernetes or other resources that are not listed, you can manually enter the plural form of the resource name. For example, if the CRD resource is AliyunLogConfig, enter AliyunLogConfigs.
Kubernetes CVE Security Risks
This report displays the Kubernetes CVE security risks that may exist in the current cluster. You can select or enter a subaccount ID, which is a RAM user account, to run a real-time query. The report displays the Kubernetes CVE security risks under the current account. For CVE details and solutions, see Vulnerability fix announcements for CVE security.
(Optional) Step 3: View detailed log records
If you need to run custom queries or analyze audit logs, you can go to the Simple Log Service console to view detailed log records.
ACK managed cluster: the data in the Logstore that corresponds to the API Server audit logs of the cluster is retained in Simple Log Service for 30 days by default. For ACK dedicated cluster, the default retention period is 365 days. To modify the default retention period of logs, see Manage Logstores.
-
Log on to the ACK console. In the left navigation pane, click Clusters.
-
On the Clusters page, click the name of your cluster. In the left navigation pane, click Cluster Information.
Click the Basic Information tab, click the Project ID that corresponds to Log Service Project, and then in the Project list area, click the Logstore named audit-${clustered}.
During cluster creation, a Logstore named
audit-${clustereid}is automatically added to the specified log Project.ImportantIndexes are already configured by default for the Logstore of audit logs. Do not modify the indexes, to prevent the reports from becoming invalid.
In the input box, enter a query and analysis statement and configure the time range of the query and analysis, such as the last 15 minutes. Then, click Search & Analyze to view the query and analysis results.
You can search audit logs in the following common ways:
Query the operation records of a RAM user: Enter the RAM user ID and click Search & Analyze.
Query the operations on a resource: Enter the name of a compute, network, storage, or access control resource of the cluster, and click Search & Analyze.
To filter out the operations of system components, enter
NOT user.username: node NOT user.username: serviceaccount NOT user.username: apiserver NOT user.username: kube-scheduler NOT user.username: kube-controller-manager, and then click Search & Analyze.
For more query and statistics methods, see Query and analysis methods of Simple Log Service.
(Optional) Step 4: Configure alerting
If you need real-time alerts for the operations on certain resources, you can use the alerting feature of Simple Log Service. Supported alerting methods include DingTalk chatbot, custom webhook, and Notification Center. For more information, see Getting started with alert settings.
Example 1: Trigger an alert when a command is run on a container
A company imposes strict limits on the use of its Kubernetes cluster and does not allow users to log on to a container or run commands on a container. If a user runs a command, an alert must be sent immediately. The alert message must include information such as the specific container that the user logged on to, the command that was run, the operator, the event ID, the time, and the source IP address of the operation.
The query statement is:
verb : create and objectRef.subresource:exec and stage: ResponseStarted | SELECT auditID as "Event ID", date_format(from_unixtime(__time__), '%Y-%m-%d %T' ) as "Operation Time", regexp_extract("requestURI", '([^\?]*)/exec\?.*', 1)as "Resource", regexp_extract("requestURI", '\?(.*)', 1)as "Command" ,"responseStatus.code" as "Status Code", CASE WHEN "user.username" != 'kubernetes-admin' then "user.username" WHEN "user.username" = 'kubernetes-admin' and regexp_like("annotations.authorization.k8s.io/reason", 'RoleBinding') then regexp_extract("annotations.authorization.k8s.io/reason", ' to User "(\w+)"', 1) ELSE 'kubernetes-admin' END as "Operator Account", CASE WHEN json_array_length(sourceIPs) = 1 then json_format(json_array_get(sourceIPs, 0)) ELSE sourceIPs END as "Source Address" order by "Operation Time" desc limit 10000The conditional expression is:
Operation Event =~ ".*".
Example 2: Trigger an alert on failed public network access to the API Server
A cluster has public network access enabled. To prevent malicious attacks, you must monitor the number of public network accesses and the failure rate. When the number of accesses reaches the threshold of 10 and the failure rate is higher than the threshold of 50%, an alert must be sent immediately. The alert message must include information such as the region to which the IP address of the user belongs, the source IP address of the operation, and whether the IP address is a high-risk IP address.
The query statement is:
* | select ip as "Source Address", total as "Access Count", round(rate * 100, 2) as "Failure Rate %", failCount as "Unauthorized Access Count", CASE when security_check_ip(ip) = 1 then 'yes' else 'no' end as "High-Risk IP", ip_to_country(ip) as "Country", ip_to_province(ip) as "Province", ip_to_city(ip) as "City", ip_to_provider(ip) as "ISP" from (select CASE WHEN json_array_length(sourceIPs) = 1 then json_format(json_array_get(sourceIPs, 0)) ELSE sourceIPs END as ip, count(1) as total, sum(CASE WHEN "responseStatus.code" < 400 then 0 ELSE 1 END) * 1.0 / count(1) as rate, count_if("responseStatus.code" = 403) as failCount from log group by ip limit 10000) where ip_to_domain(ip) != 'intranet' and ip not LIKE '%,%' ORDER by "Access Count" desc limit 10000The conditional expression is:
Source Address =~ ".*".
Related operations
Change the log Project
To migrate the API Server audit log data of a cluster to another log Project, you can use the Change Log Service Project feature in cluster auditing.
-
Log on to the ACK console. In the left navigation pane, click Clusters.
-
On the Clusters page, click the name of your cluster. In the left navigation pane, click .
On the Audit page, click the Cluster Auditing tab, and then click Change Log Service Project to migrate the cluster audit log data to another SLS Project.
Disable the cluster API Server auditing feature
If you no longer need the auditing feature of the cluster API Server, you can disable the feature as follows.
-
Log on to the ACK console. In the left navigation pane, click Clusters.
-
On the Clusters page, click the name of your cluster. In the left navigation pane, click .
On the Audit page, click the Cluster Auditing tab, and then click Disable Cluster Auditing to disable the auditing feature of the current cluster.
In ACK dedicated cluster, use a third-party logging solution
ACK recommends that you use Alibaba Cloud Simple Log Service (SLS) to record cluster audit logs. However, if you need to use a third-party log service, you can deploy the cluster without Alibaba Cloud SLS and integrate another logging solution as needed to collect and retrieve the related audit logs. The source files of the audit logs on each master node of the cluster are in standard JSON format and can be found in the /var/log/kubernetes/kubernetes.audit path.
Reference: ACK dedicated cluster API Server audit configuration overview
When you create an ACK dedicated cluster and configure the cluster components, the console selects Enable Log Service by default, which enables the API Server auditing feature, collects event data based on the audit policy, and writes the event data to the backend.
The following features involve changes to the kube-apiserver startup parameters and apply only to ACK dedicated cluster. The control planes of ACK managed cluster and ACK Serverless cluster are hosted by ACK and cannot be manually modified.
Audit policy
An audit policy defines the configuration of the auditing feature and the collection rules for requests. The collection rules for Event logs vary with the audit level (Audit Level). Audit Level includes the following types.
Audit Level | Log collection rules |
None | Events that match the rule are not collected. |
Metadata | Collects the Metadata of a request, such as the user information and the timestamp, but does not collect the request body or the response body. |
Request | Collects the Metadata and the request body of a request, but does not collect the response body. This level does not apply to non-resource requests (Non-Resource Request). |
RequestResponse | Collects the Metadata, the request body, and the response body of a request. This level does not apply to non-resource requests (Non-Resource Request). |
You can use the --audit-policy-file command flag to save the following YAML example file as a startup parameter of the API Server. After you log on to a master node, you can view the directory of the audit policy configuration file, which is /etc/kubernetes/audit-policy.yml. The following example shows a YAML audit log policy configuration file.
After a request is received, logging does not start immediately. Logging starts only after the header of the response body is sent.
The system does not audit many redundant requests, such as kube-proxy watch requests, Get requests for nodes from kubelet and system:nodes, operations on endpoints by kube components in kube-system, and Get requests for Namespaces from the API Server.
For sensitive APIs such as authentication, rbac, certificates, autoscaling, and storage, the system records the request bodies and response bodies based on read and write operations.
Audit backend
After audit events are collected, they are stored in the log file system of the Log backend. The log files are in standard JSON format. You can configure and use the following flags as the startup parameters of the API Server.
After you log on to a master node, you can view the configuration file of the API Server at /etc/kubernetes/manifests/kube-apiserver.yaml.
Configuration parameter | Description |
| Specifies the maximum number of files into which the audit log can be sharded for storage. The value is 10. |
| Specifies the maximum memory capacity of a single audit log. The value is 100 MB. |
| Specifies the output path of the audit log, which is |
| Specifies the maximum retention period of the audit log. The value is 7 days. |
| Specifies the file path used to configure the audit log policy, which is |
References
If you want to use the in-container operation auditing feature, which audits the commands that are run inside a container by using
kubectl exec, see Use the in-container operation auditing feature.For the security best practices that help enterprise security management O&M engineers use clusters, see Security best practices.