Read file content in SGX enclave

1k views Asked by At

I'm trying to read the content of a file from an enclave using OCalls.

enclave.edl:

untrusted {
        void ocall_print_string([in, string] const char *str);
        void ocall_read_IMA_file([in, string] const char *filename, [out] char *buf, [out] int *size);
};

enclave.cpp:

void printf(const char *fmt, ...) {
    ocall_print_string(fmt);
}

void read_IMA_file(const char *filename, char *buf, int *size) {
    ocall_read_IMA_file(filename, buf, size);

    printf(buf);
}

//whereas the read_IMA_file function is called with
char *buf;
int size;
read_IMA_file("test.txt", buf, &size);

implementation of ocall functions in the application:

void ocall_print_string(const char *str) {
    printf("%s\n", str);
}

void ocall_read_IMA_file(const char *filename, char *content, int *size) {
    content = (char*) malloc(sizeof(char) * 10);
    memset(content, '\0', sizeof(char) *10);
    char tmp[] = "1234567890";
    copy(&tmp[0], &tmp[9], content);

    cout << content << endl;
}

But the result I receive is the following:

123456789 (null)

I'm not sure what I'm doing wrong?

2

There are 2 answers

0
Surenthar On BEST ANSWER

In the above program, the "read_IMA_file" trusted function is called with pointer variable(OUT pointer) of type character.Here we are passing the pointer variable without any memory allocation. "read_IMA_file" initiate a OCall that allocate memory and do "Copy" operation.Now the allocated memory is valid within the untrusted region. So we are getting expected result for the "cout<

Since there is no trusted memory allocated for "content"(before calling Ocall), no copy back operation happens in "OUT" pointer during Ocall returns. So "buf" doesn't contain any valid data while doing "print(buf)" after Ocall returns in trusted region.

Please try with valid OUT pointer to character buffer(with some memory allocation) or IN and OUT pointer to String buffer.

0
Richard Li On

If you expect it to output 1234567890, then you may need to malloc(11) instead of malloc(10), plus the way you are using copy may contain a bug too.

copy(&tmp[0], &tmp[9], content); is copying 123456789 to the content, it exclude the the last iterator &tmp[9] as I understand. For more detail, you may want to look at: http://www.cplusplus.com/reference/algorithm/copy/

Also, I think you are not reading in any content from file "test.txt" either.