Re: [PATCH 3/7] rust: security: add abstraction for secctx

From: Benno Lossin
Date: Sat Dec 02 2023 - 05:03:45 EST


On 12/1/23 11:48, Alice Ryhl wrote:
> Benno Lossin <benno.lossin@xxxxxxxxx> writes:
>> On 11/29/23 14:11, Alice Ryhl wrote:
>>> + /// Returns the bytes for this security context.
>>> + pub fn as_bytes(&self) -> &[u8] {
>>> + let mut ptr = self.secdata;
>>> + if ptr.is_null() {
>>> + // Many C APIs will use null pointers for strings of length zero, but
>>
>> I would just write that the secctx API uses null pointers to denote a
>> string of length zero.
>
> I don't actually know whether it can ever be null, I just wanted to stay
> on the safe side.

I see, can someone from the C side confirm/refute this?

I found the comment a bit weird, since it is phrased in a general way.
If it turns out that the pointer can never be null, maybe use `NonNull`
instead (I would then also move the length check into the constructor)?
You can probably also do this if the pointer is allowed to be null,
assuming that you then do not need to call `security_release_secctx`.

>>> + // `slice::from_raw_parts` doesn't allow the pointer to be null even if the length is
>>> + // zero. Replace the pointer with a dangling but non-null pointer in this case.
>>> + debug_assert_eq!(self.seclen, 0);
>>
>> I am feeling a bit uncomfortable with this, why can't we just return
>> an empty slice in this case?
>
> I can do that, but to be clear, what I'm doing here is also definitely
> okay.

Yes it is okay, but I see this similar to avoiding `unsafe` code when it
can be done safely. In this example we are not strictly avoiding any
`unsafe` code, but we are avoiding a codepath with `unsafe` code. You
should of course still keep the `debug_assert_eq`.

--
Cheers,
Benno