Skip to contentSkip to conversation

mm: security: ro protection for dynamic data

RFC PATCH Superseded Igor Stoppa 6 participants 25 messages Jan 30, 2018 – Feb 12, 2018

Subsystems (7)

v12 of 21 Superseded Latest is v21 →

lore
Share & tools
lore
#0 lore raw

v12 cover mm: security: ro protection for dynamic data

This patch-set introduces the possibility of protecting memory that has been allocated dynamically.

The memory is managed in pools: when a memory pool is turned into R/O, all the memory that is part of it, will become R/O.

A R/O pool can be destroyed, to recover its memory, but it cannot be turned back into R/W mode.

This is intentional. This feature is meant for data that doesn't need further modifications after initialization.

However the data might need to be released, for example as part of module unloading.
To do this, the memory must first be freed, then the pool can be destroyed.

An example is provided, in the form of self-testing.

Changes since the v11 version:
[http://www.openwall.com/lists/kernel-hardening/2018/01/24/4]

- restricted access to sysfs entries created (444 -> 400)
- more explicit reference to documentation
- couple of typos

Igor Stoppa (6):
genalloc: track beginning of allocations
genalloc: selftest
struct page: add field for vm_struct
Protectable Memory
Documentation for Pmalloc
Pmalloc: self-test

 Documentation/core-api/pmalloc.txt | 104 ++++++++
 include/linux/genalloc-selftest.h  |  30 +++
 include/linux/genalloc.h           |   5 +-
 include/linux/mm_types.h           |   1 +
 include/linux/pmalloc.h            | 216 ++++++++++++++++
 include/linux/vmalloc.h            |   1 +
 init/main.c                        |   2 +
 lib/Kconfig                        |  15 ++
 lib/Makefile                       |   1 +
 lib/genalloc-selftest.c            | 402 +++++++++++++++++++++++++++++
 lib/genalloc.c                     | 444 +++++++++++++++++++++----------
 mm/Kconfig                         |   7 +
 mm/Makefile                        |   2 +
 mm/pmalloc-selftest.c              |  65 +++++
 mm/pmalloc-selftest.h              |  30 +++
 mm/pmalloc.c                       | 516 +++++++++++++++++++++++++++++++++++++
 mm/usercopy.c                      |  25 +-
 mm/vmalloc.c                       |  18 +-
 18 files changed, 1744 insertions(+), 140 deletions(-)
 create mode 100644 Documentation/core-api/pmalloc.txt
 create mode 100644 include/linux/genalloc-selftest.h
 create mode 100644 include/linux/pmalloc.h
 create mode 100644 lib/genalloc-selftest.c
 create mode 100644 mm/pmalloc-selftest.c
 create mode 100644 mm/pmalloc-selftest.h
 create mode 100644 mm/pmalloc.c
Signature · 1 line
2.9.3
#1 lore raw

PATCH v12 1/6 genalloc: track beginning of allocations

The genalloc library is only capable of tracking if a certain unit of allocation is in use or not.

It is not capable of discerning where the memory associated to an allocation request begins and where it ends.

The reason is that units of allocations are tracked by using a bitmap, where each bit represents that the unit is either allocated (1) or available (0).

The user of the API must keep track of how much space was requested, if it ever needs to be freed.

This can cause errors being undetected.
Ex:
* Only a subset of the memory provided to an allocation request is freed
* The memory from a subsequent allocation is freed
* The memory being freed doesn't start at the beginning of an allocation.

The bitmap is used because it allows to perform lockless read/write access, where this is supported by hw through cmpxchg. Similarly, it is possible to scan the bitmap for a sufficiently long sequence of zeros, to identify zones available for allocation.

--

This patch doubles the space reserved in the bitmap for each allocation. By using 2 bits per allocation, it is possible to encode also the information of where the allocation starts:
(msb to the left, lsb to the right, in the following "dictionary")

11: first allocation unit in the allocation
10: any subsequent allocation unit (if any) in the allocation 00: available allocation unit
01: invalid

Ex, with the same notation as above - MSb.......LSb:

...000010111100000010101011 <-- Read in this direction.

    \__|\__|\|\____|\______|
       |   | |     |       \___ 4 used allocation units
       |   | |     \___________ 3 empty allocation units
       |   | \_________________ 1 used allocation unit
       |   \___________________ 2 used allocation units
       \_______________________ 2 empty allocation units

Because of the encoding, the previous lockless operations are still possible. The only caveat is to change the parameter of the zero-finding function which establishes the alignment at which to perform the test for first zero.
The original value of the parameter is 0, meaning that an allocation can start at any point in the bitmap, while the new value is 1, meaning that allocations can start only at even places (bit 0, bit 2, etc.) The number of zeroes to look for, must therefore be doubled.

When it's time to free the memory associated to an allocation request, it's a matter of checking if the corresponding allocation unit is really the beginning of an allocation (both bits are set to 1). Looking for the ending can also be performed locklessly. It's sufficient to identify the first mapped allocation unit that is represented either as free (00) or busy (11).
Even if the allocation status should change in the meanwhile, it doesn't matter, since it can only transition between free (00) and first-allocated (11).

The parameter indicating to the *_free() function the size of the space that should be freed is not currently removed, to facilitate the transition, but it is verified, whenever it is not zero.
If it is set to zero, then the free function will autonomously decide the size to be free, by scanning the bitmap.

About the implementation: the patch introduces the concept of "bitmap entry", which has a 1:1 mapping with allocation units, while the code being patched has a 1:1 mapping between allocation units and bits.

This means that, now, the bitmap can be extended (by following powers of 2), to track also other properties of the allocations, if ever needed.

---
 include/linux/genalloc.h |   2 +-
 lib/genalloc.c           | 417 ++++++++++++++++++++++++++++++++---------------
 2 files changed, 288 insertions(+), 131 deletions(-)
include/linux/genalloc.h +1 -1
index 872f930..0377681 100644
@@ -76,7 +76,7 @@ struct gen_pool_chunk {
 	phys_addr_t phys_addr;		/* physical starting address of memory chunk */
 	unsigned long start_addr;	/* start address of memory chunk */
 	unsigned long end_addr;		/* end address of memory chunk (inclusive) */
-	unsigned long bits[0];		/* bitmap for allocating memory chunk */
+	unsigned long entries[0];	/* bitmap for allocating memory chunk */
 };
 
 /*
lib/genalloc.c +287 -130

603 lines not on this page · raw message

Signature · 1 line
2.9.3
#2 lore raw

PATCH v12 2/6 genalloc: selftest

In reply to Igor Stoppa

Introduce a set of macros for writing concise test cases for genalloc.

The test cases are meant to provide regression testing, when working on new functionality for genalloc.

Primarily they are meant to confirm that the various allocation strategy will continue to work as expected.

The execution of the self testing is controlled through a Kconfig option.

---
 include/linux/genalloc-selftest.h |  30 +++
 init/main.c                       |   2 +
 lib/Kconfig                       |  15 ++
 lib/Makefile                      |   1 +
 lib/genalloc-selftest.c           | 402 ++++++++++++++++++++++++++++++++++++++
 5 files changed, 450 insertions(+)
 create mode 100644 include/linux/genalloc-selftest.h
 create mode 100644 lib/genalloc-selftest.c
include/linux/genalloc-selftest.h new file +30 -0
new file mode 100644
index 0000000..7af1901
@@ -0,0 +1,30 @@
+/*
+ * genalloc-selftest.h
+ *
+ * (C) Copyright 2017 Huawei Technologies Co. Ltd.
+ * Author: Igor Stoppa <[email protected]>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; version 2
+ * of the License.
+ */
+
+
+#ifndef __GENALLOC_SELFTEST_H__
+#define __GENALLOC_SELFTEST_H__
+
+
+#ifdef CONFIG_GENERIC_ALLOCATOR_SELFTEST
+
+#include <linux/genalloc.h>
+
+void genalloc_selftest(void);
+
+#else
+
+static inline void genalloc_selftest(void){};
+
+#endif
+
+#endif
init/main.c +2 -0
index a8100b9..fb844aa 100644
@@ -89,6 +89,7 @@
 #include <linux/io.h>
 #include <linux/cache.h>
 #include <linux/rodata_test.h>
+#include <linux/genalloc-selftest.h>
 
 #include <asm/io.h>
 #include <asm/bugs.h>
@@ -660,6 +661,7 @@ asmlinkage __visible void __init start_kernel(void)
 	 */
 	mem_encrypt_init();
 
+	genalloc_selftest();
 #ifdef CONFIG_BLK_DEV_INITRD
 	if (initrd_start && !initrd_below_start_ok &&
 	    page_to_pfn(virt_to_page((void *)initrd_start)) < min_low_pfn) {
lib/Kconfig +15 -0
index c5e84fb..430026d0 100644
@@ -287,6 +287,21 @@ config DECOMPRESS_LZ4
 config GENERIC_ALLOCATOR
 	bool
 
+config GENERIC_ALLOCATOR_SELFTEST
+	bool "genalloc tester"
+	default n
+	select GENERIC_ALLOCATOR
+	help
+	  Enable automated testing of the generic allocator.
+	  The testing is primarily for the tracking of allocated space.
+
+config GENERIC_ALLOCATOR_SELFTEST_VERBOSE
+	bool "make the genalloc tester more verbose"
+	default n
+	select GENERIC_ALLOCATOR_SELFTEST
+	help
+	  More information will be displayed during the self-testing.
+
 #
 # reed solomon support is select'ed if needed
 #
lib/Makefile +1 -0
index d11c48e..ba06e83 100644
@@ -108,6 +108,7 @@ obj-$(CONFIG_LIBCRC32C)	+= libcrc32c.o
 obj-$(CONFIG_CRC8)	+= crc8.o
 obj-$(CONFIG_XXHASH)	+= xxhash.o
 obj-$(CONFIG_GENERIC_ALLOCATOR) += genalloc.o
+obj-$(CONFIG_GENERIC_ALLOCATOR_SELFTEST) += genalloc-selftest.o
 
 obj-$(CONFIG_842_COMPRESS) += 842/
 obj-$(CONFIG_842_DECOMPRESS) += 842/
lib/genalloc-selftest.c new file +402 -0

402 lines not on this page · raw message

Signature · 1 line
2.9.3
#3 lore raw

PATCH v12 3/6 struct page: add field for vm_struct

In reply to Igor Stoppa

When a page is used for virtual memory, it is often necessary to obtian a handler to the corresponding vm_struct, which refers to the virtually continuous area generated when invoking vmalloc.

The struct page has a "mapping" field, which can be re-used, to store a pointer to the parent area. This will avoid more expensive searches.

As example, the function find_vm_area is reimplemented, to take advantage of the newly introduced field.

---
 include/linux/mm_types.h |  1 +
 mm/vmalloc.c             | 18 +++++++++++++-----
 2 files changed, 14 insertions(+), 5 deletions(-)
include/linux/mm_types.h +1 -0
index cfd0ac4..2abd540 100644
@@ -56,6 +56,7 @@ struct page {
 		void *s_mem;			/* slab first object */
 		atomic_t compound_mapcount;	/* first tail page */
 		/* page_deferred_list().next	 -- second tail page */
+		struct vm_struct *area;
 	};
 
 	/* Second double word */
mm/vmalloc.c +13 -5
index 6739420..44c5dfc 100644
@@ -1466,13 +1466,16 @@ struct vm_struct *get_vm_area_caller(unsigned long size, unsigned long flags,
  */
 struct vm_struct *find_vm_area(const void *addr)
 {
-	struct vmap_area *va;
+	struct page *page;
 
-	va = find_vmap_area((unsigned long)addr);
-	if (va && va->flags & VM_VM_AREA)
-		return va->vm;
+	if (unlikely(!is_vmalloc_addr(addr)))
+		return NULL;
 
-	return NULL;
+	page = vmalloc_to_page(addr);
+	if (unlikely(!page))
+		return NULL;
+
+	return page->area;
 }
 
 /**
@@ -1536,6 +1539,7 @@ static void __vunmap(const void *addr, int deallocate_pages)
 			struct page *page = area->pages[i];
 
 			BUG_ON(!page);
+			page->area = NULL;
 			__free_pages(page, 0);
 		}
 
@@ -1744,6 +1748,7 @@ void *__vmalloc_node_range(unsigned long size, unsigned long align,
 			const void *caller)
 {
 	struct vm_struct *area;
+	unsigned int page_counter;
 	void *addr;
 	unsigned long real_size = size;
 
@@ -1769,6 +1774,9 @@ void *__vmalloc_node_range(unsigned long size, unsigned long align,
 
 	kmemleak_vmalloc(area, size, gfp_mask);
 
+	for (page_counter = 0; page_counter < area->nr_pages; page_counter++)
+		area->pages[page_counter]->area = area;
+
 	return addr;
 
 fail:
Signature · 1 line
2.9.3
#4 lore raw

Re: [PATCH 3/6] struct page: add field for vm_struct

mm/vmalloc.c void *__vmalloc_node_range(unsigned long size, unsigned long align, · line 1780

Quoted 8 lines · Igor Stoppa
mm/vmalloc.c +3 -0
@@ -1769,6 +1774,9 @@ void *__vmalloc_node_range(unsigned long size, unsigned long align,
 
 	kmemleak_vmalloc(area, size, gfp_mask);
 
+	for (page_counter = 0; page_counter < area->nr_pages; page_counter++)
+		area->pages[page_counter]->area = area;
+
 	return addr;

Well this introduces significant overhead for large sized allocation. Does this not matter because the areas are small?

Would it not be better to use compound page allocations here? page_head(whatever) gets you the head page where you can store all sorts of information about the chunk of memory.

#5 lore raw

Re: [PATCH 3/6] struct page: add field for vm_struct

Quoted 6 lines · Christopher Lameter
Quoted 4 lines · Igor Stoppa
mm/vmalloc.c +0 -0
@@ -1769,6 +1774,9 @@ void *__vmalloc_node_range(unsigned long size, unsigned long align,
 
 	kmemleak_vmalloc(area, size, gfp_mask);
 
Quoted 7 lines

mm/vmalloc.c void *__vmalloc_node_range(unsigned long size, unsigned long align, · line 1780

Quoted 4 lines
mm/vmalloc.c +3 -0
+	for (page_counter = 0; page_counter < area->nr_pages; page_counter++)
+		area->pages[page_counter]->area = area;
+
 	return addr;

Well this introduces significant overhead for large sized allocation. Does this not matter because the areas are small?

Relatively significant?
I do not object to your comment, but in practice i see that:

- vmalloc is used relatively little
- allocations do not seem to be huge
- there seem to be way larger overheads in the handling of virtual pages (see my proposal for the LFS/m summit, about collapsing struct vm_struct and struct vmap_area)

Quoted 3 lines

Would it not be better to use compound page allocations here? page_head(whatever) gets you the head page where you can store all sorts of information about the chunk of memory.

Can you please point me to this function/macro? I don't seem to be able to find it, at least not in 4.15

During hardened user copy permission check, I need to confirm if the memory range that would be exposed to userspace is a legitimate sub-range of a pmalloc allocation.

So, I start with the pair (address, size) and I must end up to something I can compare it against.
The idea here is to pass through struct_page and then the related vm_struct/vmap_area, which already has the information about the specific chunk of virtual memory.

I cannot comment on your proposal because I do not know where to find the reference you made, or maybe I do not understand what you mean :-(

--
igor

#6 lore raw

Re: [PATCH 3/6] struct page: add field for vm_struct

Quoted 7 lines · Igor Stoppa
Quoted 3 lines · Christopher Lameter

Would it not be better to use compound page allocations here? page_head(whatever) gets you the head page where you can store all sorts of information about the chunk of memory.

Can you please point me to this function/macro? I don't seem to be able to find it, at least not in 4.15

IIUC, he means PageHead(), which is also hard to grep for, since it is a constructed name, via Page##uname in include/linux/page-flags.h:

__PAGEFLAG(Head, head, PF_ANY) CLEARPAGEFLAG(Head, head, PF_ANY)

-Kees

Signature · 2 lines
Kees Cook
Pixel Security
#7 lore raw

Re: [PATCH 3/6] struct page: add field for vm_struct

Quoted 4 lines · Kees Cook

IIUC, he means PageHead(), which is also hard to grep for, since it is a constructed name, via Page##uname in include/linux/page-flags.h:

__PAGEFLAG(Head, head, PF_ANY) CLEARPAGEFLAG(Head, head, PF_ANY)

Thank you, I'll try to provide a meaningful reply soon, but I'll be AFK during most of next 2 weeks, so it might be delayed :-(

--
igor

#8 lore raw

Re: [PATCH 3/6] struct page: add field for vm_struct

In reply to Igor Stoppa
Quoted 6 lines · Igor Stoppa
Quoted 3 lines

Would it not be better to use compound page allocations here? page_head(whatever) gets you the head page where you can store all sorts of information about the chunk of memory.

Can you please point me to this function/macro? I don't seem to be able to find it, at least not in 4.15

Ok its compound_head(). See also the use in the SLAB and SLUB allocator.

Quoted 3 lines

During hardened user copy permission check, I need to confirm if the memory range that would be exposed to userspace is a legitimate sub-range of a pmalloc allocation.

If you save the size in the head page struct then you could do that pretty fast.

Quoted 2 lines

I cannot comment on your proposal because I do not know where to find the reference you made, or maybe I do not understand what you mean :-(

compund pages are higher order pages that are handled as a single page by the VM. See https://lwn.net/Articles/619514/

#9 lore raw

Re: [PATCH 3/6] struct page: add field for vm_struct

Quoted 3 lines · Christopher Lameter
Quoted 1 line · Igor Stoppa
Quoted 1 line

Would it not be better to use compound page allocations here?

[...]

Quoted 8 lines

Ok its compound_head(). See also the use in the SLAB and SLUB allocator.

Quoted 3 lines

During hardened user copy permission check, I need to confirm if the memory range that would be exposed to userspace is a legitimate sub-range of a pmalloc allocation.

If you save the size in the head page struct then you could do that pretty fast.

Ok, now I get what you mean.
But it doesn't seem to fit the intended use case, for other reasons (maybe the same, from 2 different POV):

- compound pages are aggregates of regular pages, in numbers that are powers of 2, while the amount of pages to allocate is not known upfront. One *could* give a hint to pmalloc about how many pages to allocate every time there is a need to grow the pool.
Iow it would be the size of a chunk. But I'm afraid the granularity would still be pretty low, so maybe it would be 2-4 times less.

- the property of the compound page will affect the property of all the pages in the compound, so when one is write protected, it can generate a lot of wasted memory, if there is too much slack (because of the order) With vmalloc, I can allocate any number of pages, minimizing the waste.

Finally, there was a discussion about optimization:
http://www.openwall.com/lists/kernel-hardening/2017/08/07/2

The patch I sent does indeed take advantage of the new information, not just for pmalloc use.

I have not measured if/where/what there is gain, but it does look like the extra info can be exploited also elsewhere.

--
igor

#10 lore raw

Re: [PATCH 3/6] struct page: add field for vm_struct

Quoted 4 lines · Igor Stoppa

- the property of the compound page will affect the property of all the pages in the compound, so when one is write protected, it can generate a lot of wasted memory, if there is too much slack (because of the order) With vmalloc, I can allocate any number of pages, minimizing the waste.

I thought the intend here is to create a pool where the whole pool becomes RO?

#11 lore raw

Re: [PATCH 3/6] struct page: add field for vm_struct

Quoted 9 lines · Christopher Lameter
Quoted 4 lines · Igor Stoppa

- the property of the compound page will affect the property of all the pages in the compound, so when one is write protected, it can generate a lot of wasted memory, if there is too much slack (because of the order) With vmalloc, I can allocate any number of pages, minimizing the waste.

I thought the intend here is to create a pool where the whole pool becomes RO?

Yes, but why would I force the number of pages in the pool to be a power of 2, when it can be any number?

If a need, say, 17 pages, I would have to allocate 32.
But it can be worse than that.
Since the size of the overall allocated memory is not known upfront, I wold have a problem to decide how many pages to allocate, every time there is need to grow the pool.

Or push the problem to the user of the API, who might be equally unaware.

Notice that there is already a function (prealloc) available to the user of the API, if the size is known upfront.

So I do not really see how using compound pages would make memory utilization better or even not worse.

--
igor

#12 lore raw

Re: [PATCH 3/6] struct page: add field for vm_struct

In reply to Igor Stoppa
Quoted 9 lines · Igor Stoppa
mm/vmalloc.c +1 -0
@@ -1744,6 +1748,7 @@ void *__vmalloc_node_range(unsigned long size, unsigned long align,
 			const void *caller)
 {
 	struct vm_struct *area;
+	unsigned int page_counter;
 	void *addr;
 	unsigned long real_size = size;
 

mm/vmalloc.c void *__vmalloc_node_range(unsigned long size, unsigned long align, · line 1781

Quoted 8 lines
mm/vmalloc.c +3 -0
@@ -1769,6 +1774,9 @@ void *__vmalloc_node_range(unsigned long size, unsigned long align,
 
 	kmemleak_vmalloc(area, size, gfp_mask);
 
+	for (page_counter = 0; page_counter < area->nr_pages; page_counter++)
+		area->pages[page_counter]->area = area;
+
 	return addr;
 

LOCAL variable names should be short, and to the point. If you have some random integer loop counter, it should probably be called ``i``. Calling it ``loop_counter`` is non-productive, if there is no chance of it being mis-understood. Similarly, ``tmp`` can be just about any type of variable that is used to hold a temporary value.

(Documentation/process/coding-style.rst)

#13 lore raw

Re: [PATCH 3/6] struct page: add field for vm_struct

On 06/02/18 14:37, Matthew Wilcox wrote:

[...]

Quoted 1 line

LOCAL variable names should be short, and to the point.

[...]

Quoted 1 line

(Documentation/process/coding-style.rst)

ok, will do, thanks for the pointer!

--
igor

#14 lore raw

PATCH v12 4/6 Protectable Memory

In reply to Igor Stoppa

The MMU available in many systems running Linux can often provide R/O protection to the memory pages it handles.

However, the MMU-based protection works efficiently only when said pages contain exclusively data that will not need further modifications.

Statically allocated variables can be segregated into a dedicated section, but this does not sit very well with dynamically allocated ones.

Dynamic allocation does not provide, currently, any means for grouping variables in memory pages that would contain exclusively data suitable for conversion to read only access mode.

The allocator here provided (pmalloc - protectable memory allocator) introduces the concept of pools of protectable memory.

A module can request a pool and then refer any allocation request to the pool handler it has received.

Once all the chunks of memory associated to a specific pool are initialized, the pool can be protected.

After this point, the pool can only be destroyed (it is up to the module to avoid any further references to the memory from the pool, after the destruction is invoked).

The latter case is mainly meant for releasing memory, when a module is unloaded.

A module can have as many pools as needed, for example to support the protection of data that is initialized in sufficiently distinct phases.

---
 include/linux/genalloc.h |   3 +
 include/linux/pmalloc.h  | 216 ++++++++++++++++++++
 include/linux/vmalloc.h  |   1 +
 lib/genalloc.c           |  27 +++
 mm/Makefile              |   1 +
 mm/pmalloc.c             | 513 +++++++++++++++++++++++++++++++++++++++++++++++
 mm/usercopy.c            |  25 ++-
 7 files changed, 782 insertions(+), 4 deletions(-)
 create mode 100644 include/linux/pmalloc.h
 create mode 100644 mm/pmalloc.c
include/linux/genalloc.h +3 -0
index 0377681..a486a26 100644
@@ -121,6 +121,9 @@ extern unsigned long gen_pool_alloc_algo(struct gen_pool *, size_t,
 extern void *gen_pool_dma_alloc(struct gen_pool *pool, size_t size,
 		dma_addr_t *dma);
 extern void gen_pool_free(struct gen_pool *, unsigned long, size_t);
+
+extern void gen_pool_flush_chunk(struct gen_pool *pool,
+				 struct gen_pool_chunk *chunk);
 extern void gen_pool_for_each_chunk(struct gen_pool *,
 	void (*)(struct gen_pool *, struct gen_pool_chunk *, void *), void *);
 extern size_t gen_pool_avail(struct gen_pool *);
include/linux/pmalloc.h new file +216 -0

216 lines not on this page · raw message

include/linux/vmalloc.h +1 -0
index 1e5d8c3..e8171b6 100644
@@ -20,6 +20,7 @@ struct notifier_block;		/* in notifier.h */
 #define VM_UNINITIALIZED	0x00000020	/* vm_struct is not fully initialized */
 #define VM_NO_GUARD		0x00000040      /* don't add guard page */
 #define VM_KASAN		0x00000080      /* has allocated kasan shadow memory */
+#define VM_PMALLOC		0x00000100	/* pmalloc area - see pmalloc.txt */
 /* bits [20..32] reserved for arch specific ioremap internals */
 
 /*
lib/genalloc.c +27 -0
index dde7830..62f69b3 100644
@@ -519,6 +519,33 @@ void gen_pool_free(struct gen_pool *pool, unsigned long addr, size_t size)
 }
 EXPORT_SYMBOL(gen_pool_free);
 
+
+/**
+ * gen_pool_flush_chunk - drops all the allocations from a specific chunk
+ * @pool:	the generic memory pool
+ * @chunk:	The chunk to wipe clear.
+ *
+ * This is meant to be called only while destroying a pool. It's up to the
+ * caller to avoid races, but really, at this point the pool should have
+ * already been retired and have become unavailable for any other sort of
+ * operation.
+ */
+void gen_pool_flush_chunk(struct gen_pool *pool,
+			  struct gen_pool_chunk *chunk)
+{
+	size_t size;
+
+	if (unlikely(!(pool && chunk)))
+		return;
+
+	size = chunk->end_addr + 1 - chunk->start_addr;
+	memset(chunk->entries, 0,
+	       DIV_ROUND_UP(size >> pool->min_alloc_order * BITS_PER_ENTRY,
+			    BITS_PER_BYTE));
+	atomic_set(&chunk->avail, size);
+}
+
+
 /**
  * gen_pool_for_each_chunk - call func for every chunk of generic memory pool
  * @pool:	the generic memory pool
mm/Makefile +1 -0
index e669f02..a6a47e1 100644
@@ -65,6 +65,7 @@ obj-$(CONFIG_SPARSEMEM)	+= sparse.o
 obj-$(CONFIG_SPARSEMEM_VMEMMAP) += sparse-vmemmap.o
 obj-$(CONFIG_SLOB) += slob.o
 obj-$(CONFIG_MMU_NOTIFIER) += mmu_notifier.o
+obj-$(CONFIG_ARCH_HAS_SET_MEMORY) += pmalloc.o
 obj-$(CONFIG_KSM) += ksm.o
 obj-$(CONFIG_PAGE_POISONING) += page_poison.o
 obj-$(CONFIG_SLAB) += slab.o
mm/pmalloc.c new file +513 -0

513 lines not on this page · raw message

mm/usercopy.c +21 -4
index a9852b2..c3b1029 100644
@@ -15,6 +15,7 @@
 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
 
 #include <linux/mm.h>
+#include <linux/pmalloc.h>
 #include <linux/slab.h>
 #include <linux/sched.h>
 #include <linux/sched/task.h>
@@ -222,6 +223,7 @@ static inline const char *check_heap_object(const void *ptr, unsigned long n,
 void __check_object_size(const void *ptr, unsigned long n, bool to_user)
 {
 	const char *err;
+	int retv;
 
 	/* Skip all tests if size is zero. */
 	if (!n)
@@ -229,12 +231,12 @@ void __check_object_size(const void *ptr, unsigned long n, bool to_user)
 
 	/* Check for invalid addresses. */
 	err = check_bogus_address(ptr, n);
-	if (err)
+	if (unlikely(err))
 		goto report;
 
 	/* Check for bad heap object. */
 	err = check_heap_object(ptr, n, to_user);
-	if (err)
+	if (unlikely(err))
 		goto report;
 
 	/* Check for bad stack object. */
@@ -257,8 +259,23 @@ void __check_object_size(const void *ptr, unsigned long n, bool to_user)
 
 	/* Check for object in kernel to avoid text exposure. */
 	err = check_kernel_text_object(ptr, n);
-	if (!err)
-		return;
+	if (unlikely(err))
+		goto report;
+
+	/* Check if object is from a pmalloc chunk.
+	 */
+	retv = is_pmalloc_object(ptr, n);
+	if (unlikely(retv)) {
+		if (unlikely(!to_user)) {
+			err = "<trying to write to pmalloc object>";
+			goto report;
+		}
+		if (retv < 0) {
+			err = "<invalid pmalloc object>";
+			goto report;
+		}
+	}
+	return;
 
 report:
 	report_usercopy(ptr, n, to_user, err);
Signature · 1 line
2.9.3
#15 lore raw

Re: [PATCH 4/6] Protectable Memory

Thank you for the patch! Perhaps something to improve:

Hi Igor,

Thank you for the patch! Perhaps something to improve:

[auto build test WARNING on linus/master]
[also build test WARNING on v4.15]
[cannot apply to next-20180201]
[if your patch is applied to the wrong git tree, please drop us a note to help improve the system]

url: https://github.com/0day-ci/linux/commits/Igor-Stoppa/mm-security-ro-protection-for-dynamic-data/20180202-123437
config: i386-randconfig-x071-201804 (attached as .config)
compiler: gcc-7 (Debian 7.2.0-12) 7.2.1 20171025 reproduce:

        # save the attached .config to linux build tree
        make ARCH=i386 

All warnings (new ones prefixed by >>):

mm/pmalloc.c: In function 'pmalloc_pool_show_avail':

>> mm/pmalloc.c:71:25: warning: format '%lu' expects argument of type 'long unsigned int', but argument 3 has type 'size_t {aka unsigned int}' [-Wformat=]
     return sprintf(buf, "%lu\n", gen_pool_avail(data->pool));
                          ~~^     ~~~~~~~~~~~~~~~~~~~~~~~~~~
                          %u
   mm/pmalloc.c: In function 'pmalloc_pool_show_size':
   mm/pmalloc.c:81:25: warning: format '%lu' expects argument of type 'long unsigned int', but argument 3 has type 'size_t {aka unsigned int}' [-Wformat=]
     return sprintf(buf, "%lu\n", gen_pool_size(data->pool));
                          ~~^     ~~~~~~~~~~~~~~~~~~~~~~~~~
                          %u

vim +71 mm/pmalloc.c

    63	
    64	static ssize_t pmalloc_pool_show_avail(struct kobject *dev,
    65					       struct kobj_attribute *attr,
    66					       char *buf)
    67	{
    68		struct pmalloc_data *data;
    69	
    70		data = container_of(attr, struct pmalloc_data, attr_avail);
  > 71		return sprintf(buf, "%lu\n", gen_pool_avail(data->pool));
    72	}
    73	

---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/pipermail/kbuild-all Intel Corporation

#16 lore raw

Re: [PATCH 4/6] Protectable Memory

In reply to Igor Stoppa
Thank you for the patch! Yet something to improve:

Hi Igor,

Thank you for the patch! Yet something to improve:

[auto build test ERROR on linus/master]
[also build test ERROR on v4.15]
[cannot apply to next-20180201]
[if your patch is applied to the wrong git tree, please drop us a note to help improve the system]

url: https://github.com/0day-ci/linux/commits/Igor-Stoppa/mm-security-ro-protection-for-dynamic-data/20180202-123437
config: i386-tinyconfig (attached as .config)
compiler: gcc-7 (Debian 7.2.0-12) 7.2.1 20171025
reproduce:

        # save the attached .config to linux build tree
        make ARCH=i386 

All errors (new ones prefixed by >>):

mm/pmalloc.o: In function `pmalloc_pool_show_chunks':

>> pmalloc.c:(.text+0x50): undefined reference to `gen_pool_for_each_chunk'
   mm/pmalloc.o: In function `pmalloc_pool_show_size':
>> pmalloc.c:(.text+0x6e): undefined reference to `gen_pool_size'
   mm/pmalloc.o: In function `pmalloc_pool_show_avail':
>> pmalloc.c:(.text+0x8a): undefined reference to `gen_pool_avail'
   mm/pmalloc.o: In function `pmalloc_chunk_free':
>> pmalloc.c:(.text+0x171): undefined reference to `gen_pool_flush_chunk'
   mm/pmalloc.o: In function `pmalloc_create_pool':
>> pmalloc.c:(.text+0x19b): undefined reference to `gen_pool_create'
>> pmalloc.c:(.text+0x2bb): undefined reference to `gen_pool_destroy'
   mm/pmalloc.o: In function `pmalloc_prealloc':
>> pmalloc.c:(.text+0x350): undefined reference to `gen_pool_add_virt'
   mm/pmalloc.o: In function `pmalloc':
>> pmalloc.c:(.text+0x3a7): undefined reference to `gen_pool_alloc'

pmalloc.c:(.text+0x3f1): undefined reference to gen_pool_add_virt' pmalloc.c:(.text+0x401): undefined reference to gen_pool_alloc' mm/pmalloc.o: In function `pmalloc_destroy_pool':
pmalloc.c:(.text+0x4a1): undefined reference to gen_pool_for_each_chunk' pmalloc.c:(.text+0x4a8): undefined reference to gen_pool_destroy'

---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/pipermail/kbuild-all Intel Corporation

#17 lore raw

PATCH v12 5/6 Documentation for Pmalloc

In reply to Igor Stoppa

Detailed documentation about the protectable memory allocator.

---
 Documentation/core-api/pmalloc.txt | 104 +++++++++++++++++++++++++++++++++++++
 1 file changed, 104 insertions(+)
 create mode 100644 Documentation/core-api/pmalloc.txt
Documentation/core-api/pmalloc.txt new file +104 -0
new file mode 100644
index 0000000..934d356
@@ -0,0 +1,104 @@
+============================
+Protectable memory allocator
+============================
+
+Introduction
+------------
+
+When trying to perform an attack toward a system, the attacker typically
+wants to alter the execution flow, in a way that allows actions which
+would otherwise be forbidden.
+
+In recent years there has been lots of effort in preventing the execution
+of arbitrary code, so the attacker is progressively pushed to look for
+alternatives.
+
+If code changes are either detected or even prevented, what is left is to
+alter kernel data.
+
+As countermeasure, constant data is collected in a section which is then
+marked as readonly.
+To expand on this, also statically allocated variables which are tagged
+as __ro_after_init will receive a similar treatment.
+The difference from constant data is that such variables can be still
+altered freely during the kernel init phase.
+
+However, such solution does not address those variables which could be
+treated essentially as read-only, but whose size is not known at compile
+time or cannot be fully initialized during the init phase.
+
+
+Design
+------
+
+pmalloc builds on top of genalloc, using the same concept of memory pools
+A pool is a handle to a group of chunks of memory of various sizes.
+When created, a pool is empty. It will be populated by allocating chunks
+of memory, either when the first memory allocation request is received, or
+when a pre-allocation is performed.
+
+Either way, one or more memory pages will be obtained from vmalloc and
+registered in the pool as chunk. Subsequent requests will be satisfied by
+either using any available free space from the current chunks, or by
+allocating more vmalloc pages, should the current free space not suffice.
+
+This is the key point of pmalloc: it groups data that must be protected
+into a set of pages. The protection is performed through the mmu, which
+is a prerequisite and has a minimum granularity of one page.
+
+If the relevant variables were not grouped, there would be a problem of
+allowing writes to other variables that might happen to share the same
+page, but require further alterations over time.
+
+A pool is a group of pages that are write protected at the same time.
+Ideally, they have some high level correlation (ex: they belong to the
+same module), which justifies write protecting them all together.
+
+To keep it to a minimum, locking is left to the user of the API, in
+those cases where it's not strictly needed.
+Ideally, no further locking is required, since each module can have own
+pool (or pools), which should, for example, avoid the need for cross
+module or cross thread synchronization about write protecting a pool.
+
+The overhead of creating an additional pool is minimal: a handful of bytes
+from kmalloc space for the metadata and then what is left unused from the
+page(s) registered as chunks.
+
+Compared to plain use of vmalloc, genalloc has the advantage of tightly
+packing the allocations, reducing the number of pages used and therefore
+the pressure on the TLB. The slight overhead in execution time of the
+allocation should be mostly irrelevant, because pmalloc memory is not
+meant to be allocated/freed in tight loops. Rather it ought to be taken
+in use, initialized and write protected. Possibly destroyed.
+
+Considering that not much data is supposed to be dynamically allocated
+and then marked as read-only, it shouldn't be an issue that the address
+range for pmalloc is limited, on 32-bit systems.
+
+Regarding SMP systems, the allocations are expected to happen mostly
+during an initial transient, after which there should be no more need to
+perform cross-processor synchronizations of page tables.
+
+
+Use
+---
+
+The typical sequence, when using pmalloc, is:
+
+1. create a pool
+2. [optional] pre-allocate some memory in the pool
+3. issue one or more allocation requests to the pool
+4. initialize the memory obtained
+   - iterate over points 3 & 4 as needed -
+5. write protect the pool
+6. use in read-only mode the handlers obtained through the allocations
+7. [optional] destroy the pool
+
+
+In a scenario where, for example due to some error, part or all of the
+allocations performed at point 3 must be reverted, it is possible to free
+them, as long as point 5 has not been executed, and the pool is still
+modifiable. Such freed memory can be re-used.
+Performing a free operation on a write-protected pool will, instead,
+simply release the corresponding memory from the accounting, but it will
+be still impossible to alter its content.
Signature · 1 line
2.9.3
maintainer
#18 lore raw

Re: [PATCH 5/6] Documentation for Pmalloc

Quoted 7 lines · On Tue, 30 Jan 2018 17:14:45 +0200 Igor Stoppa <[email protected]> wrote:

Detailed documentation about the protectable memory allocator.

---
 Documentation/core-api/pmalloc.txt | 104 +++++++++++++++++++++++++++++++++++++
 1 file changed, 104 insertions(+)
 create mode 100644 Documentation/core-api/pmalloc.txt

Please don't put plain-text files into core-api - that's a directory full of RST documents. Your document is 99.9% RST already, better to just finish the job and tie it into the rest of the kernel docs.

Documentation/core-api/pmalloc.txt

Quoted 6 lines
Documentation/core-api/pmalloc.txt new file +0 -0
new file mode 100644
index 0000000..934d356
@@ -0,0 +1,104 @@

We might as well put the SPDX tag here, it's a new file.

Quoted 18 lines
Documentation/core-api/pmalloc.txt new file +18 -0
+============================
+Protectable memory allocator
+============================
+
+Introduction
+------------
+
+When trying to perform an attack toward a system, the attacker typically
+wants to alter the execution flow, in a way that allows actions which
+would otherwise be forbidden.
+
+In recent years there has been lots of effort in preventing the execution
+of arbitrary code, so the attacker is progressively pushed to look for
+alternatives.
+
+If code changes are either detected or even prevented, what is left is to
+alter kernel data.
+

Documentation/core-api/pmalloc.txt line 28

Quoted 10 lines
Documentation/core-api/pmalloc.txt new file +10 -0
+As countermeasure, constant data is collected in a section which is then
+marked as readonly.
+To expand on this, also statically allocated variables which are tagged
+as __ro_after_init will receive a similar treatment.
+The difference from constant data is that such variables can be still
+altered freely during the kernel init phase.
+
+However, such solution does not address those variables which could be
+treated essentially as read-only, but whose size is not known at compile
+time or cannot be fully initialized during the init phase.

This is all good information, but I'd suggest it belongs more in the 0/n patch posting than here. The introduction of *this* document should say what it actually covers.

Quoted 19 lines
Documentation/core-api/pmalloc.txt new file +19 -0
+
+Design
+------
+
+pmalloc builds on top of genalloc, using the same concept of memory pools
+A pool is a handle to a group of chunks of memory of various sizes.
+When created, a pool is empty. It will be populated by allocating chunks
+of memory, either when the first memory allocation request is received, or
+when a pre-allocation is performed.
+
+Either way, one or more memory pages will be obtained from vmalloc and
+registered in the pool as chunk. Subsequent requests will be satisfied by
+either using any available free space from the current chunks, or by
+allocating more vmalloc pages, should the current free space not suffice.
+
+This is the key point of pmalloc: it groups data that must be protected
+into a set of pages. The protection is performed through the mmu, which
+is a prerequisite and has a minimum granularity of one page.
+

Documentation/core-api/pmalloc.txt line 58

Quoted 10 lines
Documentation/core-api/pmalloc.txt new file +10 -0
+If the relevant variables were not grouped, there would be a problem of
+allowing writes to other variables that might happen to share the same
+page, but require further alterations over time.
+
+A pool is a group of pages that are write protected at the same time.
+Ideally, they have some high level correlation (ex: they belong to the
+same module), which justifies write protecting them all together.
+
+To keep it to a minimum, locking is left to the user of the API, in
+those cases where it's not strictly needed.

This seems like a relevant and important aspect of the API that shouldn't be buried in the middle of a section talking about random things.

Quoted 27 lines
Documentation/core-api/pmalloc.txt new file +27 -0
+Ideally, no further locking is required, since each module can have own
+pool (or pools), which should, for example, avoid the need for cross
+module or cross thread synchronization about write protecting a pool.
+
+The overhead of creating an additional pool is minimal: a handful of bytes
+from kmalloc space for the metadata and then what is left unused from the
+page(s) registered as chunks.
+
+Compared to plain use of vmalloc, genalloc has the advantage of tightly
+packing the allocations, reducing the number of pages used and therefore
+the pressure on the TLB. The slight overhead in execution time of the
+allocation should be mostly irrelevant, because pmalloc memory is not
+meant to be allocated/freed in tight loops. Rather it ought to be taken
+in use, initialized and write protected. Possibly destroyed.
+
+Considering that not much data is supposed to be dynamically allocated
+and then marked as read-only, it shouldn't be an issue that the address
+range for pmalloc is limited, on 32-bit systems.
+
+Regarding SMP systems, the allocations are expected to happen mostly
+during an initial transient, after which there should be no more need to
+perform cross-processor synchronizations of page tables.
+
+
+Use
+---
+

Documentation/core-api/pmalloc.txt line 95

Quoted 10 lines
Documentation/core-api/pmalloc.txt new file +10 -0
+The typical sequence, when using pmalloc, is:
+
+1. create a pool
+2. [optional] pre-allocate some memory in the pool
+3. issue one or more allocation requests to the pool
+4. initialize the memory obtained
+   - iterate over points 3 & 4 as needed -
+5. write protect the pool
+6. use in read-only mode the handlers obtained through the allocations
+7. [optional] destroy the pool

So one gets this far, but has no actual idea of how to do these things. Which leads me to wonder: what is this document for? Who are you expecting to read it?

You could improve things a lot by (once again) going to RST and using directives to bring in the kerneldoc comments from the source (which, I note, do exist). But I'd suggest rethinking this document and its audience. Most of the people reading it are likely wanting to learn how to *use* this API; I think it would be best to not leave them frustrated.

Thanks,

jon

#19 lore raw

Re: [PATCH 5/6] Documentation for Pmalloc

Thanks for the review and apologies for the delay. Replies inlined below.

Quoted 2 lines · Jonathan Corbet

On Tue, 30 Jan 2018 17:14:45 +0200
Igor Stoppa <[email protected]> wrote:

[...]

Quoted 1 line

Please don't put plain-text files into core-api - that's a directory full

ok

Quoted 8 lines

Documentation/core-api/pmalloc.txt

Quoted 6 lines
Documentation/core-api/pmalloc.txt new file +0 -0
new file mode 100644
index 0000000..934d356
@@ -0,0 +1,104 @@

We might as well put the SPDX tag here, it's a new file.

ok, this is all new stuff to me ... I suppose I should do it also for all the other new files I create

But what is the license for the documentation? It's not code, so GPL seems wrong. Creative commons?

I just noticed a patch for checkpatch.pl about SPDX and asked the same question there.

https://lkml.org/lkml/2018/2/2/365

Quoted 6 lines
Quoted 6 lines
Documentation/core-api/pmalloc.txt new file +6 -0
+============================
+Protectable memory allocator
+============================
+
+Introduction
+------------

[...]

Quoted 3 lines

This is all good information, but I'd suggest it belongs more in the 0/n patch posting than here. The introduction of *this* document should say what it actually covers.

ok

Quoted 4 lines
Quoted 4 lines
Documentation/core-api/pmalloc.txt new file +3 -0
+
+Design
+------

[...]

Quoted 5 lines

Documentation/core-api/pmalloc.txt line 58

Quoted 2 lines
Documentation/core-api/pmalloc.txt new file +2 -0
+To keep it to a minimum, locking is left to the user of the API, in
+those cases where it's not strictly needed.

This seems like a relevant and important aspect of the API that shouldn't be buried in the middle of a section talking about random things.

I'll move it to the Use section.

[...]

Quoted 9 lines
Quoted 9 lines
Documentation/core-api/pmalloc.txt new file +9 -0
+Use
+---
+
+The typical sequence, when using pmalloc, is:
+
+1. create a pool
+2. [optional] pre-allocate some memory in the pool
+3. issue one or more allocation requests to the pool
+4. initialize the memory obtained
Quoted 8 lines
Quoted 4 lines

+ - iterate over points 3 & 4 as needed -
+5. write protect the pool
+6. use in read-only mode the handlers obtained through the allocations +7. [optional] destroy the pool

So one gets this far, but has no actual idea of how to do these things. Which leads me to wonder: what is this document for? Who are you expecting to read it?

I will add a reference to the selftest file.
In practice it can also work as example.

Quoted 5 lines

You could improve things a lot by (once again) going to RST and using directives to bring in the kerneldoc comments from the source (which, I note, do exist). But I'd suggest rethinking this document and its audience. Most of the people reading it are likely wanting to learn how to *use* this API; I think it would be best to not leave them frustrated.

ok, the example route should be more explicative.

--
thanks again for the review, igor

#20 lore raw

Re: [PATCH 5/6] Documentation for Pmalloc

Quoted 2 lines · Igor Stoppa

But what is the license for the documentation? It's not code, so GPL seems wrong. Creative commons?

I've done this as the first line of my new documentation files:

.. SPDX-License-Identifier: CC-BY-SA-4.0

I think this is the CC license that's closest in spirit to the GPL without the unintended consequences of the GPL when used on documentation. The GFDL seems to be out of favour these days.

maintainer
#21 lore raw

Re: [PATCH 5/6] Documentation for Pmalloc

Quoted 7 lines · On Fri, 9 Feb 2018 19:37:14 -0800 Matthew Wilcox <[email protected]> wrote:

I've done this as the first line of my new documentation files:

.. SPDX-License-Identifier: CC-BY-SA-4.0

I think this is the CC license that's closest in spirit to the GPL without the unintended consequences of the GPL when used on documentation. The GFDL seems to be out of favour these days.

I think that's a great license. I still fear that it is not suitable for kernel documentation, though, especially when we produce documents that include significant text from the (GPL-licensed) kernel source. The result is almost certainly not distributable, and I don't think that's a good thing. The GPL is not perfect for documentation, but I don't think that we have a better alternative for in-kernel docs.

jon

#22 lore raw

License documentation

Quoted 11 lines · Jonathan Corbet
Quoted 7 lines · On Fri, 9 Feb 2018 19:37:14 -0800 Matthew Wilcox <[email protected]> wrote:

I've done this as the first line of my new documentation files:

.. SPDX-License-Identifier: CC-BY-SA-4.0

I think this is the CC license that's closest in spirit to the GPL without the unintended consequences of the GPL when used on documentation. The GFDL seems to be out of favour these days.

Quoted 6 lines

I think that's a great license. I still fear that it is not suitable for kernel documentation, though, especially when we produce documents that include significant text from the (GPL-licensed) kernel source. The result is almost certainly not distributable, and I don't think that's a good thing. The GPL is not perfect for documentation, but I don't think that we have a better alternative for in-kernel docs.

That's a reasonable concern. I've read other reasonable concerns about the unintended effects of using the GPL to produce a printed book (eg can you print it in a proprietary font, do you have to provide an electronic version of the text, and so on). I fear these wise words still ring true:

But the real problem is that we as a community lack a copyleft license that works well for both code and text. About the only thing that even comes close to working is putting the documentation under the GPL as well, but the GPL is a poor fit for text. Nonetheless, it may be the best we have in cases where GPL-licensed code is to be incorporated into documentation.

I dare suggest another possibility: that we create a further exception to the license that the kernel is distributed under. Something along these lines:

Documentation [1] extracted from files marked as GPL [2] may be distributed under the terms of the CC-BY-SA-4.0 license.

[1] This includes text explicitly marked for extraction using the kernel-doc tool. It may include short example code sequences. It does not include code that would normally be expected to be compiled.

[2] GPL-2.0, GPL-2.0+, GPL-1.0+, LGPL-2.0, LGPL-2.0+, LGPL-2.1, LGPL-2.1+

We'd want to run it by a lawyer, of course, to have them check for unintended consequences.

#23 lore raw

PATCH v12 6/6 Pmalloc: self-test

In reply to Igor Stoppa

Add basic self-test functionality for pmalloc.

---
 lib/genalloc.c        |  2 +-
 mm/Kconfig            |  7 ++++++
 mm/Makefile           |  1 +
 mm/pmalloc-selftest.c | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++
 mm/pmalloc-selftest.h | 30 ++++++++++++++++++++++++
 mm/pmalloc.c          |  9 ++++---
 6 files changed, 110 insertions(+), 4 deletions(-)
 create mode 100644 mm/pmalloc-selftest.c
 create mode 100644 mm/pmalloc-selftest.h
lib/genalloc.c +1 -1
index 62f69b3..7ba2ec9 100644
@@ -542,7 +542,7 @@ void gen_pool_flush_chunk(struct gen_pool *pool,
 	memset(chunk->entries, 0,
 	       DIV_ROUND_UP(size >> pool->min_alloc_order * BITS_PER_ENTRY,
 			    BITS_PER_BYTE));
-	atomic_set(&chunk->avail, size);
+	atomic_long_set(&chunk->avail, size);
 }
 
 
mm/Kconfig +7 -0
index 03ff770..f0c960e 100644
@@ -765,3 +765,10 @@ config GUP_BENCHMARK
 	  performance of get_user_pages_fast().
 
 	  See tools/testing/selftests/vm/gup_benchmark.c
+
+config PROTECTABLE_MEMORY_SELFTEST
+	bool "Run self test for pmalloc memory allocator"
+	default n
+	help
+	  Tries to verify that pmalloc works correctly and that the memory
+	  is effectively protected.
mm/Makefile +1 -0
index a6a47e1..1e76a9b 100644
@@ -66,6 +66,7 @@ obj-$(CONFIG_SPARSEMEM_VMEMMAP) += sparse-vmemmap.o
 obj-$(CONFIG_SLOB) += slob.o
 obj-$(CONFIG_MMU_NOTIFIER) += mmu_notifier.o
 obj-$(CONFIG_ARCH_HAS_SET_MEMORY) += pmalloc.o
+obj-$(CONFIG_PROTECTABLE_MEMORY_SELFTEST) += pmalloc-selftest.o
 obj-$(CONFIG_KSM) += ksm.o
 obj-$(CONFIG_PAGE_POISONING) += page_poison.o
 obj-$(CONFIG_SLAB) += slab.o
mm/pmalloc-selftest.c new file +65 -0

65 lines not on this page · raw message

mm/pmalloc-selftest.h new file +30 -0
new file mode 100644
index 0000000..3673d23
@@ -0,0 +1,30 @@
+/*
+ * pmalloc-selftest.h
+ *
+ * (C) Copyright 2018 Huawei Technologies Co. Ltd.
+ * Author: Igor Stoppa <[email protected]>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; version 2
+ * of the License.
+ */
+
+
+#ifndef __PMALLOC_SELFTEST_H__
+#define __PMALLOC_SELFTEST_H__
+
+
+#ifdef CONFIG_PROTECTABLE_MEMORY_SELFTEST
+
+#include <linux/pmalloc.h>
+
+void pmalloc_selftest(void);
+
+#else
+
+static inline void pmalloc_selftest(void){};
+
+#endif
+
+#endif
mm/pmalloc.c +6 -3
index a64ac49..73387d7 100644
@@ -25,6 +25,8 @@
 #include <asm/cacheflush.h>
 #include <asm/page.h>
 
+#include "pmalloc-selftest.h"
+
 /**
  * pmalloc_data contains the data specific to a pmalloc pool,
  * in a format compatible with the design of gen_alloc.
@@ -152,7 +154,7 @@ static void pmalloc_disconnect(struct pmalloc_data *data,
 do { \
 	sysfs_attr_init(&data->attr_##attr_name.attr); \
 	data->attr_##attr_name.attr.name = #attr_name; \
-	data->attr_##attr_name.attr.mode = VERIFY_OCTAL_PERMISSIONS(0444); \
+	data->attr_##attr_name.attr.mode = VERIFY_OCTAL_PERMISSIONS(0400); \
 	data->attr_##attr_name.show = pmalloc_pool_show_##attr_name; \
 } while (0)
 
@@ -335,7 +337,7 @@ bool pmalloc_prealloc(struct gen_pool *pool, size_t size)
 
 	return true;
 abort:
-	vfree(chunk);
+	vfree_atomic(chunk);
 	return false;
 
 }
@@ -401,7 +403,7 @@ void *pmalloc(struct gen_pool *pool, size_t size, gfp_t gfp)
 abort:
 	untag_chunk(chunk);
 free:
-	vfree(chunk);
+	vfree_atomic(chunk);
 	return NULL;
 }
 
@@ -508,6 +510,7 @@ static int __init pmalloc_late_init(void)
 		}
 	}
 	mutex_unlock(&pmalloc_mutex);
+	pmalloc_selftest();
 	return 0;
 }
 late_initcall(pmalloc_late_init);
Signature · 1 line
2.9.3
#24 lore raw

Re: [PATCH 6/6] Pmalloc: self-test

Thank you for the patch! Yet something to improve:

Hi Igor,

Thank you for the patch! Yet something to improve:

[auto build test ERROR on linus/master]
[also build test ERROR on v4.15]
[cannot apply to next-20180201]
[if your patch is applied to the wrong git tree, please drop us a note to help improve the system]

url: https://github.com/0day-ci/linux/commits/Igor-Stoppa/mm-security-ro-protection-for-dynamic-data/20180202-123437
config: xtensa-allyesconfig (attached as .config)
compiler: xtensa-linux-gcc (GCC) 7.2.0
reproduce:
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# save the attached .config to linux build tree
make.cross ARCH=xtensa

All error/warnings (new ones prefixed by >>):

mm/pmalloc-selftest.c: In function 'pmalloc_selftest':

>> mm/pmalloc-selftest.c:43:14: error: implicit declaration of function 'vmalloc'; did you mean 'kvmalloc'? [-Werror=implicit-function-declaration]
     var_vmall = vmalloc(SIZE_2);
                 ^~~~~~~
                 kvmalloc
>> mm/pmalloc-selftest.c:43:12: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
     var_vmall = vmalloc(SIZE_2);
               ^
>> mm/pmalloc-selftest.c:52:2: error: implicit declaration of function 'vfree'; did you mean 'kvfree'? [-Werror=implicit-function-declaration]
     vfree(var_vmall);
     ^~~~~
     kvfree

cc1: some warnings being treated as errors

vim +43 mm/pmalloc-selftest.c

    19	
    20	#define validate_alloc(expected, variable, size)	\
    21		pr_notice("must be " expected ": %s",		\
    22			  is_pmalloc_object(variable, size) > 0 ? "ok" : "no")
    23	
    24	#define is_alloc_ok(variable, size)	\
    25		validate_alloc("ok", variable, size)
    26	
    27	#define is_alloc_no(variable, size)	\
    28		validate_alloc("no", variable, size)
    29	
    30	void pmalloc_selftest(void)
    31	{
    32		struct gen_pool *pool_unprot;
    33		struct gen_pool *pool_prot;
    34		void *var_prot, *var_unprot, *var_vmall;
    35	
    36		pr_notice("pmalloc self-test");
    37		pool_unprot = pmalloc_create_pool("unprotected", 0);
    38		pool_prot = pmalloc_create_pool("protected", 0);
    39		BUG_ON(!(pool_unprot && pool_prot));
    40	
    41		var_unprot = pmalloc(pool_unprot,  SIZE_1 - 1, GFP_KERNEL);
    42		var_prot = pmalloc(pool_prot,  SIZE_1, GFP_KERNEL);
  > 43		var_vmall = vmalloc(SIZE_2);
    44		is_alloc_ok(var_unprot, 10);
    45		is_alloc_ok(var_unprot, SIZE_1);
    46		is_alloc_ok(var_unprot, PAGE_SIZE);
    47		is_alloc_no(var_unprot, SIZE_1 + 1);
    48		is_alloc_no(var_vmall, 10);
    49	
    50	
    51		pfree(pool_unprot, var_unprot);
  > 52		vfree(var_vmall);

---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/pipermail/kbuild-all Intel Corporation