Bluetooth: host: Prevent bt_rand calls before bt_enable

Prevent the bt_rand function from being called before bt_enable.
Depending on the implementation of bt_rand this function cannot
be called before bluetooth has been initialized. With host supplied
crypto functions the HCI LE rand command is used for example.

The use case for calling bt_id_create before bt_enable is meant for
when the application has storage for the identity instead of the stack.
So we add the requirement that the application has to have storage
for the identity resolving key (IRK) in addition when the local
device is privacy-enabled.

Signed-off-by: Joakim Andersson <joakim.andersson@nordicsemi.no>
diff --git a/include/bluetooth/bluetooth.h b/include/bluetooth/bluetooth.h
index cb7990f..2ffe38a 100644
--- a/include/bluetooth/bluetooth.h
+++ b/include/bluetooth/bluetooth.h
@@ -202,6 +202,9 @@
  * the address from and will be able to repeat the procedure on every power
  * cycle, i.e. it would be redundant to also store the information in flash.
  *
+ * Generating random static address or random IRK is not supported when calling
+ * this function before bt_enable().
+ *
  * If the application wants to have the stack randomly generate identities
  * and store them in flash for later recovery, the way to do it would be
  * to first initialize the stack (using bt_enable), then call settings_load(),
@@ -210,8 +213,8 @@
  * call bt_id_create() to create new ones.
  *
  * @param addr Address to use for the new identity. If NULL or initialized
- *             to BT_ADDR_LE_ANY the stack will generate a new static
- *             random address for the identity and copy it to the given
+ *             to BT_ADDR_LE_ANY the stack will generate a new random
+ *             static address for the identity and copy it to the given
  *             parameter upon return from this function (in case the
  *             parameter was non-NULL).
  * @param irk  Identity Resolving Key (16 bytes) to be used with this
diff --git a/subsys/bluetooth/host/hci_core.c b/subsys/bluetooth/host/hci_core.c
index d6e86ae..e7b90a3 100644
--- a/subsys/bluetooth/host/hci_core.c
+++ b/subsys/bluetooth/host/hci_core.c
@@ -6845,6 +6845,20 @@
 		return -ENOMEM;
 	}
 
+	/* bt_rand is not available before Bluetooth enable has been called */
+	if (!atomic_test_bit(bt_dev.flags, BT_DEV_ENABLE)) {
+		uint8_t zero_irk[16] = { 0 };
+
+		if (!(addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY))) {
+			return -EINVAL;
+		}
+
+		if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
+		    !(irk && memcmp(irk, zero_irk, 16))) {
+			return -EINVAL;
+		}
+	}
+
 	new_id = bt_dev.id_count++;
 	id_create(new_id, addr, irk);