Bug 3529

Summary: `add_host_to_hostfile` should take into consideration that the known_hosts file isn't terminated with a newline character.
Product: Portable OpenSSH Reporter: Mike <git+openssh>
Component: sshAssignee: Assigned to nobody <unassigned-bugs>
Status: CLOSED FIXED    
Severity: enhancement CC: djm, dtucker, git+openssh
Priority: P5    
Version: 9.1p1   
Hardware: ix86   
OS: Linux   
Bug Depends on:    
Bug Blocks: 3533    
Attachments:
Description Flags
Check for newline at end of known_hosts and add it missing
none
Check for newline at end of known_hosts and add it missing. Close FILE * if write fails.
djm: ok+
Open for reading and appending. git+openssh: ok? (dtucker)

Description Mike 2023-01-31 06:05:49 AEDT
If the known_hosts file isn't terminated with a newline character the `add_host_to_hostfile` appends the new host key to the last line which might already contain a valid host key.
Comment 1 Darren Tucker 2023-02-04 18:10:25 AEDT
Created attachment 3655 [details]
Check for newline at end of known_hosts and add it missing

Please try this patch.
Comment 2 Darren Tucker 2023-02-05 20:33:20 AEDT
Created attachment 3656 [details]
Check for newline at end of known_hosts and add it missing.  Close FILE * if write fails.

Please try this one instead.
Comment 3 Mike 2023-02-05 21:40:18 AEDT
(In reply to Darren Tucker from comment #2)
> Created attachment 3656 [details]
> Check for newline at end of known_hosts and add it missing.  Close
> FILE * if write fails.
> 
> Please try this one instead.

Patch looks good to me, I'll try it out and report back in a day or so.
Comment 4 Mike 2023-02-06 21:43:42 AEDT
Created attachment 3657 [details]
Open for reading and appending.
Comment 5 Mike 2023-02-06 21:44:55 AEDT
(In reply to Darren Tucker from comment #2)
> Created attachment 3656 [details]
> Check for newline at end of known_hosts and add it missing.  Close
> FILE * if write fails.
> 
> Please try this one instead.

I've tested it and for a file which already was terminated with a new-line it still added an extra new-line.

I've changed the open mode to `a+` since that should be used for both appending and reading the file.

I also had to change the initial fseek to `fseek(f, -1, SEEK_END)`. The docs (https://www.man7.org/linux/man-pages/man3/fopen.3.html) mention the following:

> Open for reading and appending (writing at end of file).
> The file is created if it does not exist.  Output is
> always appended to the end of the file.  POSIX is silent
> on what the initial read position is when using this mode.
> For glibc, the initial file position for reading is at the
> beginning of the file, but for Android/BSD/MacOS, the
> initial file position for reading is at the end of the
> file.

The attachement was added in my previous comment.
Comment 6 Darren Tucker 2023-02-09 21:09:34 AEDT
Applied your version, thanks.
Comment 7 Damien Miller 2023-03-17 13:43:01 AEDT
OpenSSH 9.3 has been released. Close resolved bugs