
POC de CVE-2022-0185, Docker e informe de análisis
[toc]
ID de la vulnerabilidad: CVE-2022-0185
Puntuación de la vulnerabilidad:
Producto afectado: linux kernel - fsconfig syscall
Rango de versiones afectadas: linux kernel 5.1-rc1 ~ 5.16.2
Condiciones de explotación: local en linux; tener la capacidad CAP_SYS_ADMIN (se puede obtener directamente con unshare, por lo que equivale a sin restricciones)
Efecto de la explotación: escalada de privilegios local; escape de contenedores
Obtención del código fuente: git clone git://kernel.ubuntu.com/ubuntu/ubuntu-focal.git -b Ubuntu-hwe-5.11-5.11.0-27.29_20.04.1 --depth 1
o https://mirrors.edge.kernel.org/pub/linux/kernel/v5.x/
Docker de entorno de compilación del kernel 5.X: chenaotian/kernelcompile
Docker de análisis de la vulnerabilidad: chenaotian/cve-2022-0185
se prepararon dos kernels: uno de distribución y uno compilado a medida
instalar qemu, gdb, gdb-peda, etc.
el material de la vulnerabilidad está en /root/cve-2022-0185
boot_exp.sh para iniciar el entorno de verificación y depuración del exploit, con el kernel de distribución 5.11.0-44 sin símbolosboot_poc.sh para iniciar el entorno de verificación del PoC; puede hacer fallar el kernel, pero no puede ejecutar el exploit; kernel 5.13 autocompilado con símbolosexp, código fuente de exp (autor: BitsByWill); basta con compilar exploit_fuse.Entorno qemu: https://github.com/chenaotian/CVE-2022-0185/tree/main/qemuANDexp
Entorno de ejecución del exploit en máquina virtual ubuntu20.04, que ejecuta el exploit original.
Prepare una máquina virtual ubuntu20.04 y luego cambie el kernel:```shell apt-get install linux-image-5.11.0-44-generic
grep menuentry /boot/grub/grub.cfg vim /etc/default/grub #修改 GRUB_DEFAULT 选项为上面结果中想要启动内核的下标 update-grub #如果不生效的话则直接进入/boot 目录将之前的内核相关文件(带之前内核编号的文件)全部删掉,然后启动时候报找不到内核,然后手动选择内核启动也可以
#编译exp make fuse ./exploit
Efecto de escalada de privilegios

## Principio de la vulnerabilidad
La llamada al sistema donde ocurre la vulnerabilidad es la opción de operación `FSCONFIG_SET_STRING` en `fsconfig`. Esta llamada al sistema se utiliza para realizar algunas configuraciones en el contexto de un sistema de archivos ya abierto. **El requisito previo es disponer del permiso de cap `CAP_SYS_ADMIN`:**
> El propósito principal de `fsopen` es crear un contexto de sistema de archivos, asociarlo con un descriptor de archivo y devolver el descriptor. Después de `fsopen` viene `fsconfig`; por el significado literal se puede adivinar que, mientras arriba creamos un contexto de sistema de archivos con `fsopen`, `fsconfig` probablemente se utiliza para configurar el contenido dentro de ese contexto. De hecho, `fsconfig` se dedica principalmente a esa tarea de configuración; además del contexto de sistema de archivos, también admite otros trabajos.
### Punto donde ocurre la vulnerabilidad
Primero, la vulnerabilidad aparece en la función `legacy_parse_param`:
linux-5.11\fs\fs_context.c : 502 : legacy_parse_param```c
static int legacy_parse_param(struct fs_context *fc, struct fs_parameter *param)
{
struct legacy_fs_context *ctx = fc->fs_private;
unsigned int size = ctx->data_size;
size_t len = 0;
··· ···
··· ···
switch (param->type) {
case fs_value_is_string:
len = 1 + param->size;
fallthrough;
··· ···
}
if (len > PAGE_SIZE - 2 - size) //此处边界检查有问题
return invalf(fc, "VFS: Legacy: Cumulative options too large");
if (strchr(param->key, ',') ||
(param->type == fs_value_is_string &&
memchr(param->string, ',', param->size)))
return invalf(fc, "VFS: Legacy: Option '%s' contained comma",
param->key);
if (!ctx->legacy_data) {
ctx->legacy_data = kmalloc(PAGE_SIZE, GFP_KERNEL); //在第一次时会分配一页大小
if (!ctx->legacy_data)
return -ENOMEM;
}
ctx->legacy_data[size++] = ',';
len = strlen(param->key);
memcpy(ctx->legacy_data + size, param->key, len);
size += len;
if (param->type == fs_value_is_string) {
ctx->legacy_data[size++] = '=';
memcpy(ctx->legacy_data + size, param->string, param->size); //拷贝,可能越界
size += param->size;
}
ctx->legacy_data[size] = '\0';
ctx->data_size = size;
ctx->param_type = LEGACY_FS_INDIVIDUAL_PARAMS;
return 0;
}
El punto clave está en el memcpy posterior, que copia el param->string que pasamos dentro de ctx->legacy_data. La comprobación de si la copia se desborda se encuentra en la comparación anterior (len > PAGE_SIZE - 2 - size). Esta comprobación tiene un problema: el tipo de la comparación es size_t, es decir, unsigned int. Si size > PAGE_SIZE - 2, se produce un desbordamiento de enteros que invierte el resultado, provocando que len < PAGE_SIZE - 2 - size sea verdadero, y por tanto la comprobación se supera. Después, al copiar, size es mayor que PAGE_SIZE - 2, lo que causa un desbordamiento en la copia.
Algunas estructuras de datos utilizadas:```c struct fs_context { const struct fs_context_operations ops; struct mutex uapi_mutex; / Userspace access mutex */ struct file_system_type *fs_type; void fs_private; / The filesystem's context */ void *sget_key; struct dentry root; / The root and superblock */ struct user_namespace user_ns; / The user namespace for this mount */ struct net net_ns; / The network namespace for this mount */ const struct cred cred; / The mounter's credentials / struct p_log log; / Logging buffer */ const char source; / The source name (eg. dev path) */ void security; / Linux S&M options / void s_fs_info; / Proposed s_fs_info / unsigned int sb_flags; / Proposed superblock flags (SB_) / unsigned int sb_flags_mask; / Superblock flags that were changed / unsigned int s_iflags; / OR'd with sb->s_iflags / unsigned int lsm_flags; / Information flags from the fs to the LSM / enum fs_context_purpose purpose:8; enum fs_context_phase phase:8; / The phase the context is in / bool need_free:1; / Need to call ops->free() / bool global:1; / Goes into &init_user_ns / bool oldapi:1; / Coming from mount(2) */ };
struct legacy_fs_context { char legacy_data; / Data page for legacy filesystems */ size_t data_size; enum legacy_fs_param param_type; };
struct fs_parameter { const char key; / Parameter name / enum fs_value_type type:8; / The type of value here */ union { char *string; void *blob; struct filename *name; struct file *file; }; size_t size; int dirfd; };
### Ruta de llamada
A continuación analizamos la pila de llamadas de funciones; en primer lugar, la entrada es, sin duda, la llamada al sistema `fsconfig`:
linux-5.11\fs\fsopen.c : 314 : SYSCALL_DEFINE5(fsconfig,...```c
SYSCALL_DEFINE5(fsconfig,
int, fd,
unsigned int, cmd,
const char __user *, _key,
const void __user *, _value,
int, aux)
{
struct fs_context *fc;
struct fd f;
int ret;
int lookup_flags = 0;
struct fs_parameter param = {
.type = fs_value_is_undefined,
};
··· ···
f = fdget(fd);
if (!f.file)
return -EBADF;
ret = -EINVAL;
if (f.file->f_op != &fscontext_fops)
goto out_f;