Browse Source

faux_cleanse() function

Serj Kalichev 1 year ago
parent
commit
3dcfecbc0d
3 changed files with 32 additions and 0 deletions
  1. 30 0
      faux/base/mem.c
  2. 1 0
      faux/faux.h
  3. 1 0
      faux/faux.map

+ 30 - 0
faux/base/mem.c

@@ -86,3 +86,33 @@ void *faux_zmalloc(size_t size)
 
 	return ptr;
 }
+
+
+/** Securely clean memory buffer.
+ *
+ * If buffer is used for some crypto data then it's better to cleanse memory
+ * before freing. It's not enough to nullify it. Instead fill it with pseudo
+ * random numbers.
+ *
+ * @param [in] ptr Pointer
+ * @param [in] size Size of memory (in bytes) to clean it.
+ */
+
+void faux_cleanse(void *ptr, size_t size)
+{
+	static unsigned char cleanse_ctr = 0; // It must be static
+	unsigned char *p = (unsigned char *)ptr;
+	size_t loop = size;
+	size_t ctr = cleanse_ctr;
+
+	while(loop) {
+		*p = (unsigned char)ctr;
+		p++;
+		ctr += (17 + ((size_t)p & 0x0f));
+		loop--;
+	}
+	p = (unsigned char *)memchr(ptr, (unsigned char)ctr, size);
+	if (p)
+		ctr += 63 + (size_t)p;
+	cleanse_ctr = (unsigned char)ctr;
+}

+ 1 - 0
faux/faux.h

@@ -90,6 +90,7 @@ void faux_free(void *ptr);
 void *faux_malloc(size_t size);
 void faux_bzero(void *ptr, size_t size);
 void *faux_zmalloc(size_t size);
+void faux_cleanse(void *ptr, size_t size);
 
 // I/O
 ssize_t faux_write(int fd, const void *buf, size_t n);

+ 1 - 0
faux/faux.map

@@ -95,6 +95,7 @@ FAUX_2.0 {
 		faux_malloc;
 		faux_bzero;
 		faux_zmalloc;
+		faux_cleanse;
 
 		faux_write;
 		faux_read;