Search code examples
c++file-iointelenclavesgx

Read file content in SGX enclave


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?


Solution

  • 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.