Skip to content

macOS use SecRandomCopyBytes instead of getentropy #20466

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 5, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 4 additions & 17 deletions lib/std/sysrand.nim
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
## | :--- | ----: |
## | Windows | `BCryptGenRandom`_ |
## | Linux | `getrandom`_ |
## | MacOSX | `getentropy`_ |
## | MacOSX | `SecRandomCopyBytes`_ |
## | iOS | `SecRandomCopyBytes`_ |
## | OpenBSD | `getentropy openbsd`_ |
## | FreeBSD | `getrandom freebsd`_ |
Expand Down Expand Up @@ -66,7 +66,7 @@ when defined(nimPreviewSlimSystem):
import std/assertions

const
batchImplOS = defined(freebsd) or defined(openbsd) or defined(zephyr) or (defined(macosx) and not defined(ios))
batchImplOS = defined(freebsd) or defined(openbsd) or defined(zephyr)
batchSize {.used.} = 256

when batchImplOS:
Expand Down Expand Up @@ -231,8 +231,8 @@ elif defined(freebsd):
proc getRandomImpl(p: pointer, size: int): int {.inline.} =
result = getrandom(p, csize_t(size), 0)

elif defined(ios):
{.passL: "-framework Security".}
elif defined(ios) or defined(macosx):
{.passl: "-framework Security".}

const errSecSuccess = 0 ## No error.

Expand All @@ -254,19 +254,6 @@ elif defined(ios):

result = secRandomCopyBytes(nil, csize_t(size), addr dest[0])

elif defined(macosx):
const sysrandomHeader = """#include <Availability.h>
#include <sys/random.h>
"""

proc getentropy(p: pointer, size: csize_t): cint {.importc: "getentropy", header: sysrandomHeader.}
# getentropy() fills a buffer with random data, which can be used as input
# for process-context pseudorandom generators like arc4random(3).
# The maximum buffer size permitted is 256 bytes.

proc getRandomImpl(p: pointer, size: int): int {.inline.} =
result = getentropy(p, csize_t(size)).int

else:
template urandomImpl(result: var int, dest: var openArray[byte]) =
let size = dest.len
Expand Down