Why doesn't readlink return a null-terminated value?

851 Views Asked by At

Both The Single UNIX ® Specification, Version 2 (1997) and The Open Group Base Specifications Issue 6 (2004) require that readlink would not place a null-terminated value in buffer:

APPLICATION USAGE

Conforming applications should not assume that the returned contents of the symbolic link are null-terminated.

What are the considerations in not null-terminating buffer? Couldn't it pose a security risk when readlink isn't properly used?

2

There are 2 best solutions below

0
KamilCuk On BEST ANSWER

What are the considerations in not null-terminating buffer?

As indicated by the documentation, portability. Most probably there exists(-ed?) wide used implementations of readlink that do not null-terminate the buffer.

Couldn't it pose a security risk when readlink isn't properly used?

Every piece of bad code that uses something not properly I guess poses a security risk. The programmer is responsible for writing good code that has no security risks. The examples section of posix page shows the proper usage of readlink.

0
Zan Lynx On

I just read your links.

A simple way to make this safe to use is to write a zero into the last buffer position when the function returns. Use the returned size.

You should double check that the returned size value is not -1 and is always less than the buffer length. If it was equal then it was truncated (probably).