core.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. /*
  2. * hw_random/core.c: HWRNG core API
  3. *
  4. * Copyright 2006 Michael Buesch <m@bues.ch>
  5. * Copyright 2005 (c) MontaVista Software, Inc.
  6. *
  7. * Please read Documentation/admin-guide/hw_random.rst for details on use.
  8. *
  9. * This software may be used and distributed according to the terms
  10. * of the GNU General Public License, incorporated herein by reference.
  11. */
  12. #include <linux/delay.h>
  13. #include <linux/device.h>
  14. #include <linux/err.h>
  15. #include <linux/fs.h>
  16. #include <linux/hw_random.h>
  17. #include <linux/kernel.h>
  18. #include <linux/kthread.h>
  19. #include <linux/miscdevice.h>
  20. #include <linux/module.h>
  21. #include <linux/random.h>
  22. #include <linux/rcupdate.h>
  23. #include <linux/sched.h>
  24. #include <linux/sched/signal.h>
  25. #include <linux/slab.h>
  26. #include <linux/string.h>
  27. #include <linux/uaccess.h>
  28. #include <linux/workqueue.h>
  29. #define RNG_MODULE_NAME "hw_random"
  30. #define RNG_BUFFER_SIZE (SMP_CACHE_BYTES < 32 ? 32 : SMP_CACHE_BYTES)
  31. static struct hwrng __rcu *current_rng;
  32. /* the current rng has been explicitly chosen by user via sysfs */
  33. static int cur_rng_set_by_user;
  34. static struct task_struct *hwrng_fill;
  35. /* list of registered rngs */
  36. static LIST_HEAD(rng_list);
  37. /* Protects rng_list, hwrng_fill and updating on current_rng */
  38. static DEFINE_MUTEX(rng_mutex);
  39. /* Protects rng read functions, data_avail, rng_buffer and rng_fillbuf */
  40. static DEFINE_MUTEX(reading_mutex);
  41. static int data_avail;
  42. static u8 *rng_buffer, *rng_fillbuf;
  43. static unsigned short current_quality;
  44. static unsigned short default_quality = 1024; /* default to maximum */
  45. module_param(current_quality, ushort, 0644);
  46. MODULE_PARM_DESC(current_quality,
  47. "current hwrng entropy estimation per 1024 bits of input -- obsolete, use rng_quality instead");
  48. module_param(default_quality, ushort, 0644);
  49. MODULE_PARM_DESC(default_quality,
  50. "default maximum entropy content of hwrng per 1024 bits of input");
  51. static void drop_current_rng(void);
  52. static int hwrng_init(struct hwrng *rng);
  53. static int hwrng_fillfn(void *unused);
  54. static inline int rng_get_data(struct hwrng *rng, u8 *buffer, size_t size,
  55. int wait);
  56. static size_t rng_buffer_size(void)
  57. {
  58. return RNG_BUFFER_SIZE;
  59. }
  60. static void cleanup_rng_work(struct work_struct *work)
  61. {
  62. struct hwrng *rng = container_of(work, struct hwrng, cleanup_work);
  63. /*
  64. * Hold rng_mutex here so we serialize in case they set_current_rng
  65. * on rng again immediately.
  66. */
  67. mutex_lock(&rng_mutex);
  68. /* Skip if rng has been reinitialized. */
  69. if (kref_read(&rng->ref)) {
  70. mutex_unlock(&rng_mutex);
  71. return;
  72. }
  73. if (rng->cleanup)
  74. rng->cleanup(rng);
  75. complete(&rng->cleanup_done);
  76. mutex_unlock(&rng_mutex);
  77. }
  78. static inline void cleanup_rng(struct kref *kref)
  79. {
  80. struct hwrng *rng = container_of(kref, struct hwrng, ref);
  81. schedule_work(&rng->cleanup_work);
  82. }
  83. static int set_current_rng(struct hwrng *rng)
  84. {
  85. struct hwrng *old_rng;
  86. int err;
  87. BUG_ON(!mutex_is_locked(&rng_mutex));
  88. err = hwrng_init(rng);
  89. if (err)
  90. return err;
  91. old_rng = rcu_dereference_protected(current_rng,
  92. lockdep_is_held(&rng_mutex));
  93. rcu_assign_pointer(current_rng, rng);
  94. if (old_rng) {
  95. synchronize_rcu();
  96. kref_put(&old_rng->ref, cleanup_rng);
  97. }
  98. /* if necessary, start hwrng thread */
  99. if (!hwrng_fill) {
  100. hwrng_fill = kthread_run(hwrng_fillfn, NULL, "hwrng");
  101. if (IS_ERR(hwrng_fill)) {
  102. pr_err("hwrng_fill thread creation failed\n");
  103. hwrng_fill = NULL;
  104. }
  105. }
  106. return 0;
  107. }
  108. static void drop_current_rng(void)
  109. {
  110. struct hwrng *rng;
  111. rng = rcu_dereference_protected(current_rng,
  112. lockdep_is_held(&rng_mutex));
  113. if (!rng)
  114. return;
  115. RCU_INIT_POINTER(current_rng, NULL);
  116. synchronize_rcu();
  117. if (hwrng_fill) {
  118. kthread_stop(hwrng_fill);
  119. hwrng_fill = NULL;
  120. }
  121. /* decrease last reference for triggering the cleanup */
  122. kref_put(&rng->ref, cleanup_rng);
  123. }
  124. /* Returns NULL or refcounted hwrng */
  125. static struct hwrng *get_current_rng_nolock(void)
  126. {
  127. struct hwrng *rng;
  128. rng = rcu_dereference_protected(current_rng,
  129. lockdep_is_held(&rng_mutex));
  130. if (rng)
  131. kref_get(&rng->ref);
  132. return rng;
  133. }
  134. static struct hwrng *get_current_rng(void)
  135. {
  136. struct hwrng *rng;
  137. rcu_read_lock();
  138. rng = rcu_dereference(current_rng);
  139. if (rng)
  140. kref_get(&rng->ref);
  141. rcu_read_unlock();
  142. return rng;
  143. }
  144. static void put_rng(struct hwrng *rng)
  145. {
  146. if (rng)
  147. kref_put(&rng->ref, cleanup_rng);
  148. }
  149. static int hwrng_init(struct hwrng *rng)
  150. {
  151. if (kref_get_unless_zero(&rng->ref))
  152. goto skip_init;
  153. if (rng->init) {
  154. int ret;
  155. ret = rng->init(rng);
  156. if (ret)
  157. return ret;
  158. }
  159. kref_init(&rng->ref);
  160. reinit_completion(&rng->cleanup_done);
  161. skip_init:
  162. current_quality = rng->quality; /* obsolete */
  163. return 0;
  164. }
  165. static int rng_dev_open(struct inode *inode, struct file *filp)
  166. {
  167. /* enforce read-only access to this chrdev */
  168. if ((filp->f_mode & FMODE_READ) == 0)
  169. return -EINVAL;
  170. if (filp->f_mode & FMODE_WRITE)
  171. return -EINVAL;
  172. return 0;
  173. }
  174. static inline int rng_get_data(struct hwrng *rng, u8 *buffer, size_t size,
  175. int wait) {
  176. int present;
  177. BUG_ON(!mutex_is_locked(&reading_mutex));
  178. if (rng->read) {
  179. int err;
  180. err = rng->read(rng, buffer, size, wait);
  181. if (WARN_ON_ONCE(err > 0 && err > size))
  182. err = size;
  183. return err;
  184. }
  185. if (rng->data_present)
  186. present = rng->data_present(rng, wait);
  187. else
  188. present = 1;
  189. if (present)
  190. return rng->data_read(rng, (u32 *)buffer);
  191. return 0;
  192. }
  193. static ssize_t rng_dev_read(struct file *filp, char __user *buf,
  194. size_t size, loff_t *offp)
  195. {
  196. u8 buffer[RNG_BUFFER_SIZE];
  197. ssize_t ret = 0;
  198. int err = 0;
  199. int bytes_read, len;
  200. struct hwrng *rng;
  201. while (size) {
  202. rng = get_current_rng();
  203. if (!rng) {
  204. err = -ENODEV;
  205. goto out;
  206. }
  207. if (mutex_lock_interruptible(&reading_mutex)) {
  208. err = -ERESTARTSYS;
  209. goto out_put;
  210. }
  211. if (!data_avail) {
  212. bytes_read = rng_get_data(rng, rng_buffer,
  213. rng_buffer_size(),
  214. !(filp->f_flags & O_NONBLOCK));
  215. if (bytes_read < 0) {
  216. err = bytes_read;
  217. goto out_unlock_reading;
  218. } else if (bytes_read == 0 &&
  219. (filp->f_flags & O_NONBLOCK)) {
  220. err = -EAGAIN;
  221. goto out_unlock_reading;
  222. }
  223. data_avail = bytes_read;
  224. }
  225. len = data_avail;
  226. if (len) {
  227. if (len > size)
  228. len = size;
  229. data_avail -= len;
  230. memcpy(buffer, rng_buffer + data_avail, len);
  231. }
  232. mutex_unlock(&reading_mutex);
  233. put_rng(rng);
  234. if (len) {
  235. if (copy_to_user(buf + ret, buffer, len)) {
  236. err = -EFAULT;
  237. goto out;
  238. }
  239. size -= len;
  240. ret += len;
  241. }
  242. if (need_resched())
  243. schedule_timeout_interruptible(1);
  244. if (signal_pending(current)) {
  245. err = -ERESTARTSYS;
  246. goto out;
  247. }
  248. }
  249. out:
  250. memzero_explicit(buffer, sizeof(buffer));
  251. return ret ? : err;
  252. out_unlock_reading:
  253. mutex_unlock(&reading_mutex);
  254. out_put:
  255. put_rng(rng);
  256. goto out;
  257. }
  258. static const struct file_operations rng_chrdev_ops = {
  259. .owner = THIS_MODULE,
  260. .open = rng_dev_open,
  261. .read = rng_dev_read,
  262. .llseek = noop_llseek,
  263. };
  264. static const struct attribute_group *rng_dev_groups[];
  265. static struct miscdevice rng_miscdev = {
  266. .minor = HWRNG_MINOR,
  267. .name = RNG_MODULE_NAME,
  268. .nodename = "hwrng",
  269. .fops = &rng_chrdev_ops,
  270. .groups = rng_dev_groups,
  271. };
  272. static int enable_best_rng(void)
  273. {
  274. struct hwrng *rng, *cur_rng, *new_rng = NULL;
  275. int ret = -ENODEV;
  276. BUG_ON(!mutex_is_locked(&rng_mutex));
  277. /* no rng to use? */
  278. if (list_empty(&rng_list)) {
  279. drop_current_rng();
  280. cur_rng_set_by_user = 0;
  281. return 0;
  282. }
  283. /* use the rng which offers the best quality */
  284. list_for_each_entry(rng, &rng_list, list) {
  285. if (!new_rng || rng->quality > new_rng->quality)
  286. new_rng = rng;
  287. }
  288. cur_rng = rcu_dereference_protected(current_rng,
  289. lockdep_is_held(&rng_mutex));
  290. ret = ((new_rng == cur_rng) ? 0 : set_current_rng(new_rng));
  291. if (!ret)
  292. cur_rng_set_by_user = 0;
  293. return ret;
  294. }
  295. static ssize_t rng_current_store(struct device *dev,
  296. struct device_attribute *attr,
  297. const char *buf, size_t len)
  298. {
  299. int err;
  300. struct hwrng *rng, *new_rng;
  301. err = mutex_lock_interruptible(&rng_mutex);
  302. if (err)
  303. return -ERESTARTSYS;
  304. if (sysfs_streq(buf, "")) {
  305. err = enable_best_rng();
  306. } else if (sysfs_streq(buf, "none")) {
  307. cur_rng_set_by_user = 1;
  308. drop_current_rng();
  309. } else {
  310. list_for_each_entry(rng, &rng_list, list) {
  311. if (sysfs_streq(rng->name, buf)) {
  312. err = set_current_rng(rng);
  313. if (!err)
  314. cur_rng_set_by_user = 1;
  315. break;
  316. }
  317. }
  318. }
  319. new_rng = get_current_rng_nolock();
  320. mutex_unlock(&rng_mutex);
  321. if (new_rng)
  322. put_rng(new_rng);
  323. return err ? : len;
  324. }
  325. static ssize_t rng_current_show(struct device *dev,
  326. struct device_attribute *attr,
  327. char *buf)
  328. {
  329. ssize_t ret;
  330. struct hwrng *rng;
  331. rng = get_current_rng();
  332. ret = sysfs_emit(buf, "%s\n", rng ? rng->name : "none");
  333. put_rng(rng);
  334. return ret;
  335. }
  336. static ssize_t rng_available_show(struct device *dev,
  337. struct device_attribute *attr,
  338. char *buf)
  339. {
  340. int err;
  341. struct hwrng *rng;
  342. err = mutex_lock_interruptible(&rng_mutex);
  343. if (err)
  344. return -ERESTARTSYS;
  345. buf[0] = '\0';
  346. list_for_each_entry(rng, &rng_list, list) {
  347. strlcat(buf, rng->name, PAGE_SIZE);
  348. strlcat(buf, " ", PAGE_SIZE);
  349. }
  350. strlcat(buf, "none\n", PAGE_SIZE);
  351. mutex_unlock(&rng_mutex);
  352. return strlen(buf);
  353. }
  354. static ssize_t rng_selected_show(struct device *dev,
  355. struct device_attribute *attr,
  356. char *buf)
  357. {
  358. return sysfs_emit(buf, "%d\n", cur_rng_set_by_user);
  359. }
  360. static ssize_t rng_quality_show(struct device *dev,
  361. struct device_attribute *attr,
  362. char *buf)
  363. {
  364. ssize_t ret;
  365. struct hwrng *rng;
  366. rng = get_current_rng();
  367. if (!rng) /* no need to put_rng */
  368. return -ENODEV;
  369. ret = sysfs_emit(buf, "%hu\n", rng->quality);
  370. put_rng(rng);
  371. return ret;
  372. }
  373. static ssize_t rng_quality_store(struct device *dev,
  374. struct device_attribute *attr,
  375. const char *buf, size_t len)
  376. {
  377. struct hwrng *rng;
  378. u16 quality;
  379. int ret = -EINVAL;
  380. if (len < 2)
  381. return -EINVAL;
  382. ret = mutex_lock_interruptible(&rng_mutex);
  383. if (ret)
  384. return -ERESTARTSYS;
  385. ret = kstrtou16(buf, 0, &quality);
  386. if (ret || quality > 1024) {
  387. ret = -EINVAL;
  388. goto out;
  389. }
  390. rng = rcu_dereference_protected(current_rng, lockdep_is_held(&rng_mutex));
  391. if (!rng) {
  392. ret = -ENODEV;
  393. goto out;
  394. }
  395. rng->quality = quality;
  396. current_quality = quality; /* obsolete */
  397. /* the best available RNG may have changed */
  398. ret = enable_best_rng();
  399. out:
  400. mutex_unlock(&rng_mutex);
  401. return ret ? ret : len;
  402. }
  403. static DEVICE_ATTR_RW(rng_current);
  404. static DEVICE_ATTR_RO(rng_available);
  405. static DEVICE_ATTR_RO(rng_selected);
  406. static DEVICE_ATTR_RW(rng_quality);
  407. static struct attribute *rng_dev_attrs[] = {
  408. &dev_attr_rng_current.attr,
  409. &dev_attr_rng_available.attr,
  410. &dev_attr_rng_selected.attr,
  411. &dev_attr_rng_quality.attr,
  412. NULL
  413. };
  414. ATTRIBUTE_GROUPS(rng_dev);
  415. static int hwrng_fillfn(void *unused)
  416. {
  417. size_t entropy, entropy_credit = 0; /* in 1/1024 of a bit */
  418. long rc;
  419. while (!kthread_should_stop()) {
  420. unsigned short quality;
  421. struct hwrng *rng;
  422. rng = get_current_rng();
  423. if (!rng) {
  424. /*
  425. * Keep the task_struct alive until kthread_stop()
  426. * is called to avoid UAF in drop_current_rng().
  427. */
  428. while (!kthread_should_stop()) {
  429. set_current_state(TASK_INTERRUPTIBLE);
  430. if (!kthread_should_stop())
  431. schedule();
  432. }
  433. set_current_state(TASK_RUNNING);
  434. break;
  435. }
  436. mutex_lock(&reading_mutex);
  437. rc = rng_get_data(rng, rng_fillbuf,
  438. rng_buffer_size(), 1);
  439. if (current_quality != rng->quality)
  440. rng->quality = current_quality; /* obsolete */
  441. quality = rng->quality;
  442. mutex_unlock(&reading_mutex);
  443. if (rc <= 0)
  444. hwrng_msleep(rng, 10000);
  445. put_rng(rng);
  446. if (rc <= 0)
  447. continue;
  448. /* If we cannot credit at least one bit of entropy,
  449. * keep track of the remainder for the next iteration
  450. */
  451. entropy = rc * quality * 8 + entropy_credit;
  452. if ((entropy >> 10) == 0)
  453. entropy_credit = entropy;
  454. /* Outside lock, sure, but y'know: randomness. */
  455. add_hwgenerator_randomness((void *)rng_fillbuf, rc,
  456. entropy >> 10, true);
  457. }
  458. return 0;
  459. }
  460. int hwrng_register(struct hwrng *rng)
  461. {
  462. int err = -EINVAL;
  463. struct hwrng *cur_rng, *tmp;
  464. if (!rng->name || (!rng->data_read && !rng->read))
  465. goto out;
  466. mutex_lock(&rng_mutex);
  467. /* Must not register two RNGs with the same name. */
  468. err = -EEXIST;
  469. list_for_each_entry(tmp, &rng_list, list) {
  470. if (strcmp(tmp->name, rng->name) == 0)
  471. goto out_unlock;
  472. }
  473. list_add_tail(&rng->list, &rng_list);
  474. INIT_WORK(&rng->cleanup_work, cleanup_rng_work);
  475. init_completion(&rng->cleanup_done);
  476. complete(&rng->cleanup_done);
  477. init_completion(&rng->dying);
  478. /* Adjust quality field to always have a proper value */
  479. rng->quality = min3(default_quality, 1024, rng->quality ?: 1024);
  480. if (!cur_rng_set_by_user) {
  481. cur_rng = rcu_dereference_protected(current_rng,
  482. lockdep_is_held(&rng_mutex));
  483. if (!cur_rng || rng->quality > cur_rng->quality) {
  484. /*
  485. * Set new rng as current as the new rng source
  486. * provides better entropy quality and was not
  487. * chosen by userspace.
  488. */
  489. err = set_current_rng(rng);
  490. if (err)
  491. goto out_unlock;
  492. }
  493. }
  494. mutex_unlock(&rng_mutex);
  495. return 0;
  496. out_unlock:
  497. mutex_unlock(&rng_mutex);
  498. out:
  499. return err;
  500. }
  501. EXPORT_SYMBOL_GPL(hwrng_register);
  502. void hwrng_unregister(struct hwrng *rng)
  503. {
  504. struct hwrng *cur_rng;
  505. int err;
  506. mutex_lock(&rng_mutex);
  507. list_del(&rng->list);
  508. complete_all(&rng->dying);
  509. cur_rng = rcu_dereference_protected(current_rng,
  510. lockdep_is_held(&rng_mutex));
  511. if (cur_rng == rng) {
  512. err = enable_best_rng();
  513. if (err) {
  514. drop_current_rng();
  515. cur_rng_set_by_user = 0;
  516. }
  517. }
  518. mutex_unlock(&rng_mutex);
  519. wait_for_completion(&rng->cleanup_done);
  520. }
  521. EXPORT_SYMBOL_GPL(hwrng_unregister);
  522. static void devm_hwrng_release(struct device *dev, void *res)
  523. {
  524. hwrng_unregister(*(struct hwrng **)res);
  525. }
  526. static int devm_hwrng_match(struct device *dev, void *res, void *data)
  527. {
  528. struct hwrng **r = res;
  529. if (WARN_ON(!r || !*r))
  530. return 0;
  531. return *r == data;
  532. }
  533. int devm_hwrng_register(struct device *dev, struct hwrng *rng)
  534. {
  535. struct hwrng **ptr;
  536. int error;
  537. ptr = devres_alloc(devm_hwrng_release, sizeof(*ptr), GFP_KERNEL);
  538. if (!ptr)
  539. return -ENOMEM;
  540. error = hwrng_register(rng);
  541. if (error) {
  542. devres_free(ptr);
  543. return error;
  544. }
  545. *ptr = rng;
  546. devres_add(dev, ptr);
  547. return 0;
  548. }
  549. EXPORT_SYMBOL_GPL(devm_hwrng_register);
  550. void devm_hwrng_unregister(struct device *dev, struct hwrng *rng)
  551. {
  552. devres_release(dev, devm_hwrng_release, devm_hwrng_match, rng);
  553. }
  554. EXPORT_SYMBOL_GPL(devm_hwrng_unregister);
  555. long hwrng_msleep(struct hwrng *rng, unsigned int msecs)
  556. {
  557. unsigned long timeout = msecs_to_jiffies(msecs) + 1;
  558. return wait_for_completion_interruptible_timeout(&rng->dying, timeout);
  559. }
  560. EXPORT_SYMBOL_GPL(hwrng_msleep);
  561. long hwrng_yield(struct hwrng *rng)
  562. {
  563. return wait_for_completion_interruptible_timeout(&rng->dying, 1);
  564. }
  565. EXPORT_SYMBOL_GPL(hwrng_yield);
  566. static int __init hwrng_modinit(void)
  567. {
  568. int ret;
  569. /* kmalloc makes this safe for virt_to_page() in virtio_rng.c */
  570. rng_buffer = kmalloc(rng_buffer_size(), GFP_KERNEL);
  571. if (!rng_buffer)
  572. return -ENOMEM;
  573. rng_fillbuf = kmalloc(rng_buffer_size(), GFP_KERNEL);
  574. if (!rng_fillbuf) {
  575. kfree(rng_buffer);
  576. return -ENOMEM;
  577. }
  578. ret = misc_register(&rng_miscdev);
  579. if (ret) {
  580. kfree(rng_fillbuf);
  581. kfree(rng_buffer);
  582. }
  583. return ret;
  584. }
  585. static void __exit hwrng_modexit(void)
  586. {
  587. mutex_lock(&rng_mutex);
  588. WARN_ON(rcu_access_pointer(current_rng));
  589. kfree(rng_buffer);
  590. kfree(rng_fillbuf);
  591. mutex_unlock(&rng_mutex);
  592. misc_deregister(&rng_miscdev);
  593. }
  594. fs_initcall(hwrng_modinit); /* depends on misc_register() */
  595. module_exit(hwrng_modexit);
  596. MODULE_DESCRIPTION("H/W Random Number Generator (RNG) driver");
  597. MODULE_LICENSE("GPL");