Skip to content

Commit

Permalink
fixes TOCTOU bug in bap log (#937)
Browse files Browse the repository at this point in the history
* fixes TOCTOU bug in log

* protect mkdir too

* moved lock in tmp dir

* updated after review
  • Loading branch information
gitoleg authored Apr 2, 2019
1 parent 651003f commit 1554ffd
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions lib/bap/bap_log.ml
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,30 @@ let print_message ppf msg =
| Error -> eprintf "%s@\n%!" msg.message
| _ -> ()

let lock_filename logdir =
let digest = Md5.digest_string logdir in
let name = sprintf "bap-%s.lock" (Md5.to_hex digest) in
Filename.get_temp_dir_name () / name

let lock file =
let lock = Unix.openfile file Unix.[O_RDWR; O_CREAT] 0o666 in
Unix.lockf lock Unix.F_LOCK 0;
lock

let unlock lock =
Unix.lockf lock Unix.F_ULOCK 0;
Unix.close lock

let open_log_channel user_dir =
try
let log_folder = log_folder user_dir in
mkdir log_folder;
let file = log_folder / "log" in
if Sys.file_exists file
then rotate max_logs file;
let lock = lock (lock_filename log_folder) in
protect ~f:(fun () ->
mkdir log_folder;
if Sys.file_exists file
then rotate max_logs file)
~finally:(fun () -> unlock lock);
let ch = Out_channel.create file in
formatter_of_out_channel ch
with exn ->
Expand Down

0 comments on commit 1554ffd

Please sign in to comment.