af_netlink.c 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * NETLINK Kernel-user communication protocol.
  4. *
  5. * Authors: Alan Cox <alan@lxorguk.ukuu.org.uk>
  6. * Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
  7. * Patrick McHardy <kaber@trash.net>
  8. *
  9. * Tue Jun 26 14:36:48 MEST 2001 Herbert "herp" Rosmanith
  10. * added netlink_proto_exit
  11. * Tue Jan 22 18:32:44 BRST 2002 Arnaldo C. de Melo <acme@conectiva.com.br>
  12. * use nlk_sk, as sk->protinfo is on a diet 8)
  13. * Fri Jul 22 19:51:12 MEST 2005 Harald Welte <laforge@gnumonks.org>
  14. * - inc module use count of module that owns
  15. * the kernel socket in case userspace opens
  16. * socket of same protocol
  17. * - remove all module support, since netlink is
  18. * mandatory if CONFIG_NET=y these days
  19. */
  20. #include <linux/module.h>
  21. #include <linux/bpf.h>
  22. #include <linux/capability.h>
  23. #include <linux/kernel.h>
  24. #include <linux/filter.h>
  25. #include <linux/init.h>
  26. #include <linux/signal.h>
  27. #include <linux/sched.h>
  28. #include <linux/errno.h>
  29. #include <linux/string.h>
  30. #include <linux/stat.h>
  31. #include <linux/socket.h>
  32. #include <linux/un.h>
  33. #include <linux/fcntl.h>
  34. #include <linux/termios.h>
  35. #include <linux/sockios.h>
  36. #include <linux/net.h>
  37. #include <linux/fs.h>
  38. #include <linux/slab.h>
  39. #include <linux/uaccess.h>
  40. #include <linux/skbuff.h>
  41. #include <linux/netdevice.h>
  42. #include <linux/rtnetlink.h>
  43. #include <linux/proc_fs.h>
  44. #include <linux/seq_file.h>
  45. #include <linux/notifier.h>
  46. #include <linux/security.h>
  47. #include <linux/jhash.h>
  48. #include <linux/jiffies.h>
  49. #include <linux/random.h>
  50. #include <linux/bitops.h>
  51. #include <linux/mm.h>
  52. #include <linux/types.h>
  53. #include <linux/audit.h>
  54. #include <linux/mutex.h>
  55. #include <linux/vmalloc.h>
  56. #include <linux/if_arp.h>
  57. #include <linux/rhashtable.h>
  58. #include <asm/cacheflush.h>
  59. #include <linux/hash.h>
  60. #include <linux/net_namespace.h>
  61. #include <linux/nospec.h>
  62. #include <linux/btf_ids.h>
  63. #include <net/net_namespace.h>
  64. #include <net/netns/generic.h>
  65. #include <net/sock.h>
  66. #include <net/scm.h>
  67. #include <net/netlink.h>
  68. #define CREATE_TRACE_POINTS
  69. #include <trace/events/netlink.h>
  70. #include "af_netlink.h"
  71. #include "genetlink.h"
  72. struct listeners {
  73. struct rcu_head rcu;
  74. unsigned long masks[];
  75. };
  76. /* state bits */
  77. #define NETLINK_S_CONGESTED 0x0
  78. static inline int netlink_is_kernel(struct sock *sk)
  79. {
  80. return nlk_test_bit(KERNEL_SOCKET, sk);
  81. }
  82. struct netlink_table *nl_table __read_mostly;
  83. EXPORT_SYMBOL_GPL(nl_table);
  84. static DECLARE_WAIT_QUEUE_HEAD(nl_table_wait);
  85. static struct lock_class_key nlk_cb_mutex_keys[MAX_LINKS];
  86. static const char *const nlk_cb_mutex_key_strings[MAX_LINKS + 1] = {
  87. "nlk_cb_mutex-ROUTE",
  88. "nlk_cb_mutex-1",
  89. "nlk_cb_mutex-USERSOCK",
  90. "nlk_cb_mutex-FIREWALL",
  91. "nlk_cb_mutex-SOCK_DIAG",
  92. "nlk_cb_mutex-NFLOG",
  93. "nlk_cb_mutex-XFRM",
  94. "nlk_cb_mutex-SELINUX",
  95. "nlk_cb_mutex-ISCSI",
  96. "nlk_cb_mutex-AUDIT",
  97. "nlk_cb_mutex-FIB_LOOKUP",
  98. "nlk_cb_mutex-CONNECTOR",
  99. "nlk_cb_mutex-NETFILTER",
  100. "nlk_cb_mutex-IP6_FW",
  101. "nlk_cb_mutex-DNRTMSG",
  102. "nlk_cb_mutex-KOBJECT_UEVENT",
  103. "nlk_cb_mutex-GENERIC",
  104. "nlk_cb_mutex-17",
  105. "nlk_cb_mutex-SCSITRANSPORT",
  106. "nlk_cb_mutex-ECRYPTFS",
  107. "nlk_cb_mutex-RDMA",
  108. "nlk_cb_mutex-CRYPTO",
  109. "nlk_cb_mutex-SMC",
  110. "nlk_cb_mutex-23",
  111. "nlk_cb_mutex-24",
  112. "nlk_cb_mutex-25",
  113. "nlk_cb_mutex-26",
  114. "nlk_cb_mutex-27",
  115. "nlk_cb_mutex-28",
  116. "nlk_cb_mutex-29",
  117. "nlk_cb_mutex-30",
  118. "nlk_cb_mutex-31",
  119. "nlk_cb_mutex-MAX_LINKS"
  120. };
  121. static int netlink_dump(struct sock *sk, bool lock_taken);
  122. /* nl_table locking explained:
  123. * Lookup and traversal are protected with an RCU read-side lock. Insertion
  124. * and removal are protected with per bucket lock while using RCU list
  125. * modification primitives and may run in parallel to RCU protected lookups.
  126. * Destruction of the Netlink socket may only occur *after* nl_table_lock has
  127. * been acquired * either during or after the socket has been removed from
  128. * the list and after an RCU grace period.
  129. */
  130. DEFINE_RWLOCK(nl_table_lock);
  131. EXPORT_SYMBOL_GPL(nl_table_lock);
  132. static atomic_t nl_table_users = ATOMIC_INIT(0);
  133. #define nl_deref_protected(X) rcu_dereference_protected(X, lockdep_is_held(&nl_table_lock));
  134. static BLOCKING_NOTIFIER_HEAD(netlink_chain);
  135. static const struct rhashtable_params netlink_rhashtable_params;
  136. void do_trace_netlink_extack(const char *msg)
  137. {
  138. trace_netlink_extack(msg);
  139. }
  140. EXPORT_SYMBOL(do_trace_netlink_extack);
  141. static inline u32 netlink_group_mask(u32 group)
  142. {
  143. if (group > 32)
  144. return 0;
  145. return group ? 1 << (group - 1) : 0;
  146. }
  147. static struct sk_buff *netlink_to_full_skb(const struct sk_buff *skb,
  148. gfp_t gfp_mask)
  149. {
  150. unsigned int len = skb->len;
  151. struct sk_buff *new;
  152. new = alloc_skb(len, gfp_mask);
  153. if (new == NULL)
  154. return NULL;
  155. NETLINK_CB(new).portid = NETLINK_CB(skb).portid;
  156. NETLINK_CB(new).dst_group = NETLINK_CB(skb).dst_group;
  157. NETLINK_CB(new).creds = NETLINK_CB(skb).creds;
  158. skb_put_data(new, skb->data, len);
  159. return new;
  160. }
  161. static unsigned int netlink_tap_net_id;
  162. struct netlink_tap_net {
  163. struct list_head netlink_tap_all;
  164. struct mutex netlink_tap_lock;
  165. };
  166. int netlink_add_tap(struct netlink_tap *nt)
  167. {
  168. struct net *net = dev_net(nt->dev);
  169. struct netlink_tap_net *nn = net_generic(net, netlink_tap_net_id);
  170. if (unlikely(nt->dev->type != ARPHRD_NETLINK))
  171. return -EINVAL;
  172. mutex_lock(&nn->netlink_tap_lock);
  173. list_add_rcu(&nt->list, &nn->netlink_tap_all);
  174. mutex_unlock(&nn->netlink_tap_lock);
  175. __module_get(nt->module);
  176. return 0;
  177. }
  178. EXPORT_SYMBOL_GPL(netlink_add_tap);
  179. static int __netlink_remove_tap(struct netlink_tap *nt)
  180. {
  181. struct net *net = dev_net(nt->dev);
  182. struct netlink_tap_net *nn = net_generic(net, netlink_tap_net_id);
  183. bool found = false;
  184. struct netlink_tap *tmp;
  185. mutex_lock(&nn->netlink_tap_lock);
  186. list_for_each_entry(tmp, &nn->netlink_tap_all, list) {
  187. if (nt == tmp) {
  188. list_del_rcu(&nt->list);
  189. found = true;
  190. goto out;
  191. }
  192. }
  193. pr_warn("__netlink_remove_tap: %p not found\n", nt);
  194. out:
  195. mutex_unlock(&nn->netlink_tap_lock);
  196. if (found)
  197. module_put(nt->module);
  198. return found ? 0 : -ENODEV;
  199. }
  200. int netlink_remove_tap(struct netlink_tap *nt)
  201. {
  202. int ret;
  203. ret = __netlink_remove_tap(nt);
  204. synchronize_net();
  205. return ret;
  206. }
  207. EXPORT_SYMBOL_GPL(netlink_remove_tap);
  208. static __net_init int netlink_tap_init_net(struct net *net)
  209. {
  210. struct netlink_tap_net *nn = net_generic(net, netlink_tap_net_id);
  211. INIT_LIST_HEAD(&nn->netlink_tap_all);
  212. mutex_init(&nn->netlink_tap_lock);
  213. return 0;
  214. }
  215. static struct pernet_operations netlink_tap_net_ops = {
  216. .init = netlink_tap_init_net,
  217. .id = &netlink_tap_net_id,
  218. .size = sizeof(struct netlink_tap_net),
  219. };
  220. static bool netlink_filter_tap(const struct sk_buff *skb)
  221. {
  222. struct sock *sk = skb->sk;
  223. /* We take the more conservative approach and
  224. * whitelist socket protocols that may pass.
  225. */
  226. switch (sk->sk_protocol) {
  227. case NETLINK_ROUTE:
  228. case NETLINK_USERSOCK:
  229. case NETLINK_SOCK_DIAG:
  230. case NETLINK_NFLOG:
  231. case NETLINK_XFRM:
  232. case NETLINK_FIB_LOOKUP:
  233. case NETLINK_NETFILTER:
  234. case NETLINK_GENERIC:
  235. return true;
  236. }
  237. return false;
  238. }
  239. static int __netlink_deliver_tap_skb(struct sk_buff *skb,
  240. struct net_device *dev)
  241. {
  242. struct sk_buff *nskb;
  243. struct sock *sk = skb->sk;
  244. int ret = -ENOMEM;
  245. if (!net_eq(dev_net(dev), sock_net(sk)))
  246. return 0;
  247. dev_hold(dev);
  248. if (is_vmalloc_addr(skb->head))
  249. nskb = netlink_to_full_skb(skb, GFP_ATOMIC);
  250. else
  251. nskb = skb_clone(skb, GFP_ATOMIC);
  252. if (nskb) {
  253. nskb->dev = dev;
  254. nskb->protocol = htons((u16) sk->sk_protocol);
  255. nskb->pkt_type = netlink_is_kernel(sk) ?
  256. PACKET_KERNEL : PACKET_USER;
  257. skb_reset_network_header(nskb);
  258. ret = dev_queue_xmit(nskb);
  259. if (unlikely(ret > 0))
  260. ret = net_xmit_errno(ret);
  261. }
  262. dev_put(dev);
  263. return ret;
  264. }
  265. static void __netlink_deliver_tap(struct sk_buff *skb, struct netlink_tap_net *nn)
  266. {
  267. int ret;
  268. struct netlink_tap *tmp;
  269. if (!netlink_filter_tap(skb))
  270. return;
  271. list_for_each_entry_rcu(tmp, &nn->netlink_tap_all, list) {
  272. ret = __netlink_deliver_tap_skb(skb, tmp->dev);
  273. if (unlikely(ret))
  274. break;
  275. }
  276. }
  277. static void netlink_deliver_tap(struct net *net, struct sk_buff *skb)
  278. {
  279. struct netlink_tap_net *nn = net_generic(net, netlink_tap_net_id);
  280. rcu_read_lock();
  281. if (unlikely(!list_empty(&nn->netlink_tap_all)))
  282. __netlink_deliver_tap(skb, nn);
  283. rcu_read_unlock();
  284. }
  285. static void netlink_deliver_tap_kernel(struct sock *dst, struct sock *src,
  286. struct sk_buff *skb)
  287. {
  288. if (!(netlink_is_kernel(dst) && netlink_is_kernel(src)))
  289. netlink_deliver_tap(sock_net(dst), skb);
  290. }
  291. static void netlink_overrun(struct sock *sk)
  292. {
  293. if (!nlk_test_bit(RECV_NO_ENOBUFS, sk)) {
  294. if (!test_and_set_bit(NETLINK_S_CONGESTED,
  295. &nlk_sk(sk)->state)) {
  296. WRITE_ONCE(sk->sk_err, ENOBUFS);
  297. sk_error_report(sk);
  298. }
  299. }
  300. sk_drops_inc(sk);
  301. }
  302. static void netlink_rcv_wake(struct sock *sk)
  303. {
  304. struct netlink_sock *nlk = nlk_sk(sk);
  305. if (skb_queue_empty_lockless(&sk->sk_receive_queue))
  306. clear_bit(NETLINK_S_CONGESTED, &nlk->state);
  307. if (!test_bit(NETLINK_S_CONGESTED, &nlk->state))
  308. wake_up_interruptible(&nlk->wait);
  309. }
  310. static void netlink_skb_destructor(struct sk_buff *skb)
  311. {
  312. if (is_vmalloc_addr(skb->head)) {
  313. if (!skb->cloned ||
  314. !atomic_dec_return(&(skb_shinfo(skb)->dataref)))
  315. vfree_atomic(skb->head);
  316. skb->head = NULL;
  317. }
  318. if (skb->sk != NULL)
  319. sock_rfree(skb);
  320. }
  321. static void netlink_skb_set_owner_r(struct sk_buff *skb, struct sock *sk)
  322. {
  323. WARN_ON(skb->sk != NULL);
  324. skb->sk = sk;
  325. skb->destructor = netlink_skb_destructor;
  326. sk_mem_charge(sk, skb->truesize);
  327. }
  328. static void netlink_sock_destruct(struct sock *sk)
  329. {
  330. skb_queue_purge(&sk->sk_receive_queue);
  331. if (!sock_flag(sk, SOCK_DEAD)) {
  332. printk(KERN_ERR "Freeing alive netlink socket %p\n", sk);
  333. return;
  334. }
  335. WARN_ON(atomic_read(&sk->sk_rmem_alloc));
  336. WARN_ON(refcount_read(&sk->sk_wmem_alloc));
  337. WARN_ON(nlk_sk(sk)->groups);
  338. }
  339. /* This lock without WQ_FLAG_EXCLUSIVE is good on UP and it is _very_ bad on
  340. * SMP. Look, when several writers sleep and reader wakes them up, all but one
  341. * immediately hit write lock and grab all the cpus. Exclusive sleep solves
  342. * this, _but_ remember, it adds useless work on UP machines.
  343. */
  344. void netlink_table_grab(void)
  345. __acquires(nl_table_lock)
  346. {
  347. might_sleep();
  348. write_lock_irq(&nl_table_lock);
  349. if (atomic_read(&nl_table_users)) {
  350. DECLARE_WAITQUEUE(wait, current);
  351. add_wait_queue_exclusive(&nl_table_wait, &wait);
  352. for (;;) {
  353. set_current_state(TASK_UNINTERRUPTIBLE);
  354. if (atomic_read(&nl_table_users) == 0)
  355. break;
  356. write_unlock_irq(&nl_table_lock);
  357. schedule();
  358. write_lock_irq(&nl_table_lock);
  359. }
  360. __set_current_state(TASK_RUNNING);
  361. remove_wait_queue(&nl_table_wait, &wait);
  362. }
  363. }
  364. void netlink_table_ungrab(void)
  365. __releases(nl_table_lock)
  366. {
  367. write_unlock_irq(&nl_table_lock);
  368. wake_up(&nl_table_wait);
  369. }
  370. static inline void
  371. netlink_lock_table(void)
  372. {
  373. unsigned long flags;
  374. /* read_lock() synchronizes us to netlink_table_grab */
  375. read_lock_irqsave(&nl_table_lock, flags);
  376. atomic_inc(&nl_table_users);
  377. read_unlock_irqrestore(&nl_table_lock, flags);
  378. }
  379. static inline void
  380. netlink_unlock_table(void)
  381. {
  382. if (atomic_dec_and_test(&nl_table_users))
  383. wake_up(&nl_table_wait);
  384. }
  385. struct netlink_compare_arg
  386. {
  387. possible_net_t pnet;
  388. u32 portid;
  389. };
  390. /* Doing sizeof directly may yield 4 extra bytes on 64-bit. */
  391. #define netlink_compare_arg_len \
  392. (offsetof(struct netlink_compare_arg, portid) + sizeof(u32))
  393. static inline int netlink_compare(struct rhashtable_compare_arg *arg,
  394. const void *ptr)
  395. {
  396. const struct netlink_compare_arg *x = arg->key;
  397. const struct netlink_sock *nlk = ptr;
  398. return nlk->portid != x->portid ||
  399. !net_eq(sock_net(&nlk->sk), read_pnet(&x->pnet));
  400. }
  401. static void netlink_compare_arg_init(struct netlink_compare_arg *arg,
  402. struct net *net, u32 portid)
  403. {
  404. memset(arg, 0, sizeof(*arg));
  405. write_pnet(&arg->pnet, net);
  406. arg->portid = portid;
  407. }
  408. static struct sock *__netlink_lookup(struct netlink_table *table, u32 portid,
  409. struct net *net)
  410. {
  411. struct netlink_compare_arg arg;
  412. netlink_compare_arg_init(&arg, net, portid);
  413. return rhashtable_lookup_fast(&table->hash, &arg,
  414. netlink_rhashtable_params);
  415. }
  416. static int __netlink_insert(struct netlink_table *table, struct sock *sk)
  417. {
  418. struct netlink_compare_arg arg;
  419. netlink_compare_arg_init(&arg, sock_net(sk), nlk_sk(sk)->portid);
  420. return rhashtable_lookup_insert_key(&table->hash, &arg,
  421. &nlk_sk(sk)->node,
  422. netlink_rhashtable_params);
  423. }
  424. static struct sock *netlink_lookup(struct net *net, int protocol, u32 portid)
  425. {
  426. struct netlink_table *table = &nl_table[protocol];
  427. struct sock *sk;
  428. rcu_read_lock();
  429. sk = __netlink_lookup(table, portid, net);
  430. if (sk)
  431. sock_hold(sk);
  432. rcu_read_unlock();
  433. return sk;
  434. }
  435. static const struct proto_ops netlink_ops;
  436. static void
  437. netlink_update_listeners(struct sock *sk)
  438. {
  439. struct netlink_table *tbl = &nl_table[sk->sk_protocol];
  440. unsigned long mask;
  441. unsigned int i;
  442. struct listeners *listeners;
  443. listeners = nl_deref_protected(tbl->listeners);
  444. if (!listeners)
  445. return;
  446. for (i = 0; i < NLGRPLONGS(tbl->groups); i++) {
  447. mask = 0;
  448. sk_for_each_bound(sk, &tbl->mc_list) {
  449. if (i < NLGRPLONGS(nlk_sk(sk)->ngroups))
  450. mask |= nlk_sk(sk)->groups[i];
  451. }
  452. listeners->masks[i] = mask;
  453. }
  454. /* this function is only called with the netlink table "grabbed", which
  455. * makes sure updates are visible before bind or setsockopt return. */
  456. }
  457. static int netlink_insert(struct sock *sk, u32 portid)
  458. {
  459. struct netlink_table *table = &nl_table[sk->sk_protocol];
  460. int err;
  461. lock_sock(sk);
  462. err = nlk_sk(sk)->portid == portid ? 0 : -EBUSY;
  463. if (nlk_sk(sk)->bound)
  464. goto err;
  465. /* portid can be read locklessly from netlink_getname(). */
  466. WRITE_ONCE(nlk_sk(sk)->portid, portid);
  467. sock_hold(sk);
  468. err = __netlink_insert(table, sk);
  469. if (err) {
  470. /* In case the hashtable backend returns with -EBUSY
  471. * from here, it must not escape to the caller.
  472. */
  473. if (unlikely(err == -EBUSY))
  474. err = -EOVERFLOW;
  475. if (err == -EEXIST)
  476. err = -EADDRINUSE;
  477. sock_put(sk);
  478. goto err;
  479. }
  480. /* We need to ensure that the socket is hashed and visible. */
  481. smp_wmb();
  482. /* Paired with lockless reads from netlink_bind(),
  483. * netlink_connect() and netlink_sendmsg().
  484. */
  485. WRITE_ONCE(nlk_sk(sk)->bound, portid);
  486. err:
  487. release_sock(sk);
  488. return err;
  489. }
  490. static void netlink_remove(struct sock *sk)
  491. {
  492. struct netlink_table *table;
  493. table = &nl_table[sk->sk_protocol];
  494. if (!rhashtable_remove_fast(&table->hash, &nlk_sk(sk)->node,
  495. netlink_rhashtable_params))
  496. __sock_put(sk);
  497. netlink_table_grab();
  498. if (nlk_sk(sk)->subscriptions) {
  499. __sk_del_bind_node(sk);
  500. netlink_update_listeners(sk);
  501. }
  502. if (sk->sk_protocol == NETLINK_GENERIC)
  503. atomic_inc(&genl_sk_destructing_cnt);
  504. netlink_table_ungrab();
  505. }
  506. static struct proto netlink_proto = {
  507. .name = "NETLINK",
  508. .owner = THIS_MODULE,
  509. .obj_size = sizeof(struct netlink_sock),
  510. };
  511. static int __netlink_create(struct net *net, struct socket *sock,
  512. int protocol, int kern)
  513. {
  514. struct sock *sk;
  515. struct netlink_sock *nlk;
  516. sock->ops = &netlink_ops;
  517. sk = sk_alloc(net, PF_NETLINK, GFP_KERNEL, &netlink_proto, kern);
  518. if (!sk)
  519. return -ENOMEM;
  520. sock_init_data(sock, sk);
  521. nlk = nlk_sk(sk);
  522. mutex_init(&nlk->nl_cb_mutex);
  523. lockdep_set_class_and_name(&nlk->nl_cb_mutex,
  524. nlk_cb_mutex_keys + protocol,
  525. nlk_cb_mutex_key_strings[protocol]);
  526. init_waitqueue_head(&nlk->wait);
  527. sk->sk_destruct = netlink_sock_destruct;
  528. sk->sk_protocol = protocol;
  529. return 0;
  530. }
  531. static int netlink_create(struct net *net, struct socket *sock, int protocol,
  532. int kern)
  533. {
  534. struct module *module = NULL;
  535. struct netlink_sock *nlk;
  536. int (*bind)(struct net *net, int group);
  537. void (*unbind)(struct net *net, int group);
  538. void (*release)(struct sock *sock, unsigned long *groups);
  539. int err = 0;
  540. sock->state = SS_UNCONNECTED;
  541. if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
  542. return -ESOCKTNOSUPPORT;
  543. if (protocol < 0 || protocol >= MAX_LINKS)
  544. return -EPROTONOSUPPORT;
  545. protocol = array_index_nospec(protocol, MAX_LINKS);
  546. netlink_lock_table();
  547. #ifdef CONFIG_MODULES
  548. if (!nl_table[protocol].registered) {
  549. netlink_unlock_table();
  550. request_module("net-pf-%d-proto-%d", PF_NETLINK, protocol);
  551. netlink_lock_table();
  552. }
  553. #endif
  554. if (nl_table[protocol].registered &&
  555. try_module_get(nl_table[protocol].module))
  556. module = nl_table[protocol].module;
  557. else
  558. err = -EPROTONOSUPPORT;
  559. bind = nl_table[protocol].bind;
  560. unbind = nl_table[protocol].unbind;
  561. release = nl_table[protocol].release;
  562. netlink_unlock_table();
  563. if (err < 0)
  564. goto out;
  565. err = __netlink_create(net, sock, protocol, kern);
  566. if (err < 0)
  567. goto out_module;
  568. sock_prot_inuse_add(net, &netlink_proto, 1);
  569. nlk = nlk_sk(sock->sk);
  570. nlk->module = module;
  571. nlk->netlink_bind = bind;
  572. nlk->netlink_unbind = unbind;
  573. nlk->netlink_release = release;
  574. out:
  575. return err;
  576. out_module:
  577. module_put(module);
  578. goto out;
  579. }
  580. static void deferred_put_nlk_sk(struct rcu_head *head)
  581. {
  582. struct netlink_sock *nlk = container_of(head, struct netlink_sock, rcu);
  583. struct sock *sk = &nlk->sk;
  584. kfree(nlk->groups);
  585. nlk->groups = NULL;
  586. if (!refcount_dec_and_test(&sk->sk_refcnt))
  587. return;
  588. sk_free(sk);
  589. }
  590. static int netlink_release(struct socket *sock)
  591. {
  592. struct sock *sk = sock->sk;
  593. struct netlink_sock *nlk;
  594. if (!sk)
  595. return 0;
  596. netlink_remove(sk);
  597. sock_orphan(sk);
  598. nlk = nlk_sk(sk);
  599. /*
  600. * OK. Socket is unlinked, any packets that arrive now
  601. * will be purged.
  602. */
  603. if (nlk->netlink_release)
  604. nlk->netlink_release(sk, nlk->groups);
  605. /* must not acquire netlink_table_lock in any way again before unbind
  606. * and notifying genetlink is done as otherwise it might deadlock
  607. */
  608. if (nlk->netlink_unbind) {
  609. int i;
  610. for (i = 0; i < nlk->ngroups; i++)
  611. if (test_bit(i, nlk->groups))
  612. nlk->netlink_unbind(sock_net(sk), i + 1);
  613. }
  614. if (sk->sk_protocol == NETLINK_GENERIC &&
  615. atomic_dec_return(&genl_sk_destructing_cnt) == 0)
  616. wake_up(&genl_sk_destructing_waitq);
  617. sock->sk = NULL;
  618. wake_up_interruptible_all(&nlk->wait);
  619. skb_queue_purge(&sk->sk_write_queue);
  620. if (nlk->portid && nlk->bound) {
  621. struct netlink_notify n = {
  622. .net = sock_net(sk),
  623. .protocol = sk->sk_protocol,
  624. .portid = nlk->portid,
  625. };
  626. blocking_notifier_call_chain(&netlink_chain,
  627. NETLINK_URELEASE, &n);
  628. }
  629. /* Terminate any outstanding dump */
  630. if (nlk->cb_running) {
  631. if (nlk->cb.done)
  632. nlk->cb.done(&nlk->cb);
  633. module_put(nlk->cb.module);
  634. kfree_skb(nlk->cb.skb);
  635. WRITE_ONCE(nlk->cb_running, false);
  636. }
  637. module_put(nlk->module);
  638. if (netlink_is_kernel(sk)) {
  639. netlink_table_grab();
  640. BUG_ON(nl_table[sk->sk_protocol].registered == 0);
  641. if (--nl_table[sk->sk_protocol].registered == 0) {
  642. struct listeners *old;
  643. old = nl_deref_protected(nl_table[sk->sk_protocol].listeners);
  644. RCU_INIT_POINTER(nl_table[sk->sk_protocol].listeners, NULL);
  645. kfree_rcu(old, rcu);
  646. nl_table[sk->sk_protocol].module = NULL;
  647. nl_table[sk->sk_protocol].bind = NULL;
  648. nl_table[sk->sk_protocol].unbind = NULL;
  649. nl_table[sk->sk_protocol].flags = 0;
  650. nl_table[sk->sk_protocol].registered = 0;
  651. }
  652. netlink_table_ungrab();
  653. }
  654. sock_prot_inuse_add(sock_net(sk), &netlink_proto, -1);
  655. call_rcu(&nlk->rcu, deferred_put_nlk_sk);
  656. return 0;
  657. }
  658. static int netlink_autobind(struct socket *sock)
  659. {
  660. struct sock *sk = sock->sk;
  661. struct net *net = sock_net(sk);
  662. struct netlink_table *table = &nl_table[sk->sk_protocol];
  663. s32 portid = task_tgid_vnr(current);
  664. int err;
  665. s32 rover = -4096;
  666. bool ok;
  667. retry:
  668. cond_resched();
  669. rcu_read_lock();
  670. ok = !__netlink_lookup(table, portid, net);
  671. rcu_read_unlock();
  672. if (!ok) {
  673. /* Bind collision, search negative portid values. */
  674. if (rover == -4096)
  675. /* rover will be in range [S32_MIN, -4097] */
  676. rover = S32_MIN + get_random_u32_below(-4096 - S32_MIN);
  677. else if (rover >= -4096)
  678. rover = -4097;
  679. portid = rover--;
  680. goto retry;
  681. }
  682. err = netlink_insert(sk, portid);
  683. if (err == -EADDRINUSE)
  684. goto retry;
  685. /* If 2 threads race to autobind, that is fine. */
  686. if (err == -EBUSY)
  687. err = 0;
  688. return err;
  689. }
  690. /**
  691. * __netlink_ns_capable - General netlink message capability test
  692. * @nsp: NETLINK_CB of the socket buffer holding a netlink command from userspace.
  693. * @user_ns: The user namespace of the capability to use
  694. * @cap: The capability to use
  695. *
  696. * Test to see if the opener of the socket we received the message
  697. * from had when the netlink socket was created and the sender of the
  698. * message has the capability @cap in the user namespace @user_ns.
  699. */
  700. bool __netlink_ns_capable(const struct netlink_skb_parms *nsp,
  701. struct user_namespace *user_ns, int cap)
  702. {
  703. return ((nsp->flags & NETLINK_SKB_DST) ||
  704. file_ns_capable(nsp->sk->sk_socket->file, user_ns, cap)) &&
  705. ns_capable(user_ns, cap);
  706. }
  707. EXPORT_SYMBOL(__netlink_ns_capable);
  708. /**
  709. * netlink_ns_capable - General netlink message capability test
  710. * @skb: socket buffer holding a netlink command from userspace
  711. * @user_ns: The user namespace of the capability to use
  712. * @cap: The capability to use
  713. *
  714. * Test to see if the opener of the socket we received the message
  715. * from had when the netlink socket was created and the sender of the
  716. * message has the capability @cap in the user namespace @user_ns.
  717. */
  718. bool netlink_ns_capable(const struct sk_buff *skb,
  719. struct user_namespace *user_ns, int cap)
  720. {
  721. return __netlink_ns_capable(&NETLINK_CB(skb), user_ns, cap);
  722. }
  723. EXPORT_SYMBOL(netlink_ns_capable);
  724. /**
  725. * netlink_capable - Netlink global message capability test
  726. * @skb: socket buffer holding a netlink command from userspace
  727. * @cap: The capability to use
  728. *
  729. * Test to see if the opener of the socket we received the message
  730. * from had when the netlink socket was created and the sender of the
  731. * message has the capability @cap in all user namespaces.
  732. */
  733. bool netlink_capable(const struct sk_buff *skb, int cap)
  734. {
  735. return netlink_ns_capable(skb, &init_user_ns, cap);
  736. }
  737. EXPORT_SYMBOL(netlink_capable);
  738. /**
  739. * netlink_net_capable - Netlink network namespace message capability test
  740. * @skb: socket buffer holding a netlink command from userspace
  741. * @cap: The capability to use
  742. *
  743. * Test to see if the opener of the socket we received the message
  744. * from had when the netlink socket was created and the sender of the
  745. * message has the capability @cap over the network namespace of
  746. * the socket we received the message from.
  747. */
  748. bool netlink_net_capable(const struct sk_buff *skb, int cap)
  749. {
  750. return netlink_ns_capable(skb, sock_net(skb->sk)->user_ns, cap);
  751. }
  752. EXPORT_SYMBOL(netlink_net_capable);
  753. static inline int netlink_allowed(const struct socket *sock, unsigned int flag)
  754. {
  755. return (nl_table[sock->sk->sk_protocol].flags & flag) ||
  756. ns_capable(sock_net(sock->sk)->user_ns, CAP_NET_ADMIN);
  757. }
  758. static void
  759. netlink_update_subscriptions(struct sock *sk, unsigned int subscriptions)
  760. {
  761. struct netlink_sock *nlk = nlk_sk(sk);
  762. if (nlk->subscriptions && !subscriptions)
  763. __sk_del_bind_node(sk);
  764. else if (!nlk->subscriptions && subscriptions)
  765. sk_add_bind_node(sk, &nl_table[sk->sk_protocol].mc_list);
  766. nlk->subscriptions = subscriptions;
  767. }
  768. static int netlink_realloc_groups(struct sock *sk)
  769. {
  770. struct netlink_sock *nlk = nlk_sk(sk);
  771. unsigned int groups;
  772. unsigned long *new_groups;
  773. int err = 0;
  774. netlink_table_grab();
  775. groups = nl_table[sk->sk_protocol].groups;
  776. if (!nl_table[sk->sk_protocol].registered) {
  777. err = -ENOENT;
  778. goto out_unlock;
  779. }
  780. if (nlk->ngroups >= groups)
  781. goto out_unlock;
  782. new_groups = krealloc(nlk->groups, NLGRPSZ(groups), GFP_ATOMIC);
  783. if (new_groups == NULL) {
  784. err = -ENOMEM;
  785. goto out_unlock;
  786. }
  787. memset((char *)new_groups + NLGRPSZ(nlk->ngroups), 0,
  788. NLGRPSZ(groups) - NLGRPSZ(nlk->ngroups));
  789. nlk->groups = new_groups;
  790. nlk->ngroups = groups;
  791. out_unlock:
  792. netlink_table_ungrab();
  793. return err;
  794. }
  795. static void netlink_undo_bind(int group, long unsigned int groups,
  796. struct sock *sk)
  797. {
  798. struct netlink_sock *nlk = nlk_sk(sk);
  799. int undo;
  800. if (!nlk->netlink_unbind)
  801. return;
  802. for (undo = 0; undo < group; undo++)
  803. if (test_bit(undo, &groups))
  804. nlk->netlink_unbind(sock_net(sk), undo + 1);
  805. }
  806. static int netlink_bind(struct socket *sock, struct sockaddr_unsized *addr,
  807. int addr_len)
  808. {
  809. struct sock *sk = sock->sk;
  810. struct net *net = sock_net(sk);
  811. struct netlink_sock *nlk = nlk_sk(sk);
  812. struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
  813. int err = 0;
  814. unsigned long groups;
  815. bool bound;
  816. if (addr_len < sizeof(struct sockaddr_nl))
  817. return -EINVAL;
  818. if (nladdr->nl_family != AF_NETLINK)
  819. return -EINVAL;
  820. groups = nladdr->nl_groups;
  821. /* Only superuser is allowed to listen multicasts */
  822. if (groups) {
  823. if (!netlink_allowed(sock, NL_CFG_F_NONROOT_RECV))
  824. return -EPERM;
  825. err = netlink_realloc_groups(sk);
  826. if (err)
  827. return err;
  828. }
  829. if (nlk->ngroups < BITS_PER_LONG)
  830. groups &= (1UL << nlk->ngroups) - 1;
  831. /* Paired with WRITE_ONCE() in netlink_insert() */
  832. bound = READ_ONCE(nlk->bound);
  833. if (bound) {
  834. /* Ensure nlk->portid is up-to-date. */
  835. smp_rmb();
  836. if (nladdr->nl_pid != nlk->portid)
  837. return -EINVAL;
  838. }
  839. if (nlk->netlink_bind && groups) {
  840. int group;
  841. /* nl_groups is a u32, so cap the maximum groups we can bind */
  842. for (group = 0; group < BITS_PER_TYPE(u32); group++) {
  843. if (!test_bit(group, &groups))
  844. continue;
  845. err = nlk->netlink_bind(net, group + 1);
  846. if (!err)
  847. continue;
  848. netlink_undo_bind(group, groups, sk);
  849. return err;
  850. }
  851. }
  852. /* No need for barriers here as we return to user-space without
  853. * using any of the bound attributes.
  854. */
  855. netlink_lock_table();
  856. if (!bound) {
  857. err = nladdr->nl_pid ?
  858. netlink_insert(sk, nladdr->nl_pid) :
  859. netlink_autobind(sock);
  860. if (err) {
  861. netlink_undo_bind(BITS_PER_TYPE(u32), groups, sk);
  862. goto unlock;
  863. }
  864. }
  865. if (!groups && (nlk->groups == NULL || !(u32)nlk->groups[0]))
  866. goto unlock;
  867. netlink_unlock_table();
  868. netlink_table_grab();
  869. netlink_update_subscriptions(sk, nlk->subscriptions +
  870. hweight32(groups) -
  871. hweight32(nlk->groups[0]));
  872. nlk->groups[0] = (nlk->groups[0] & ~0xffffffffUL) | groups;
  873. netlink_update_listeners(sk);
  874. netlink_table_ungrab();
  875. return 0;
  876. unlock:
  877. netlink_unlock_table();
  878. return err;
  879. }
  880. static int netlink_connect(struct socket *sock, struct sockaddr_unsized *addr,
  881. int alen, int flags)
  882. {
  883. int err = 0;
  884. struct sock *sk = sock->sk;
  885. struct netlink_sock *nlk = nlk_sk(sk);
  886. struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
  887. if (alen < sizeof(addr->sa_family))
  888. return -EINVAL;
  889. if (addr->sa_family == AF_UNSPEC) {
  890. /* paired with READ_ONCE() in netlink_getsockbyportid() */
  891. WRITE_ONCE(sk->sk_state, NETLINK_UNCONNECTED);
  892. /* dst_portid and dst_group can be read locklessly */
  893. WRITE_ONCE(nlk->dst_portid, 0);
  894. WRITE_ONCE(nlk->dst_group, 0);
  895. return 0;
  896. }
  897. if (addr->sa_family != AF_NETLINK)
  898. return -EINVAL;
  899. if (alen < sizeof(struct sockaddr_nl))
  900. return -EINVAL;
  901. if ((nladdr->nl_groups || nladdr->nl_pid) &&
  902. !netlink_allowed(sock, NL_CFG_F_NONROOT_SEND))
  903. return -EPERM;
  904. /* No need for barriers here as we return to user-space without
  905. * using any of the bound attributes.
  906. * Paired with WRITE_ONCE() in netlink_insert().
  907. */
  908. if (!READ_ONCE(nlk->bound))
  909. err = netlink_autobind(sock);
  910. if (err == 0) {
  911. /* paired with READ_ONCE() in netlink_getsockbyportid() */
  912. WRITE_ONCE(sk->sk_state, NETLINK_CONNECTED);
  913. /* dst_portid and dst_group can be read locklessly */
  914. WRITE_ONCE(nlk->dst_portid, nladdr->nl_pid);
  915. WRITE_ONCE(nlk->dst_group, ffs(nladdr->nl_groups));
  916. }
  917. return err;
  918. }
  919. static int netlink_getname(struct socket *sock, struct sockaddr *addr,
  920. int peer)
  921. {
  922. struct sock *sk = sock->sk;
  923. struct netlink_sock *nlk = nlk_sk(sk);
  924. DECLARE_SOCKADDR(struct sockaddr_nl *, nladdr, addr);
  925. nladdr->nl_family = AF_NETLINK;
  926. nladdr->nl_pad = 0;
  927. if (peer) {
  928. /* Paired with WRITE_ONCE() in netlink_connect() */
  929. nladdr->nl_pid = READ_ONCE(nlk->dst_portid);
  930. nladdr->nl_groups = netlink_group_mask(READ_ONCE(nlk->dst_group));
  931. } else {
  932. /* Paired with WRITE_ONCE() in netlink_insert() */
  933. nladdr->nl_pid = READ_ONCE(nlk->portid);
  934. netlink_lock_table();
  935. nladdr->nl_groups = nlk->groups ? nlk->groups[0] : 0;
  936. netlink_unlock_table();
  937. }
  938. return sizeof(*nladdr);
  939. }
  940. static int netlink_ioctl(struct socket *sock, unsigned int cmd,
  941. unsigned long arg)
  942. {
  943. /* try to hand this ioctl down to the NIC drivers.
  944. */
  945. return -ENOIOCTLCMD;
  946. }
  947. static struct sock *netlink_getsockbyportid(struct sock *ssk, u32 portid)
  948. {
  949. struct sock *sock;
  950. struct netlink_sock *nlk;
  951. sock = netlink_lookup(sock_net(ssk), ssk->sk_protocol, portid);
  952. if (!sock)
  953. return ERR_PTR(-ECONNREFUSED);
  954. /* Don't bother queuing skb if kernel socket has no input function */
  955. nlk = nlk_sk(sock);
  956. /* dst_portid and sk_state can be changed in netlink_connect() */
  957. if (READ_ONCE(sock->sk_state) == NETLINK_CONNECTED &&
  958. READ_ONCE(nlk->dst_portid) != nlk_sk(ssk)->portid) {
  959. sock_put(sock);
  960. return ERR_PTR(-ECONNREFUSED);
  961. }
  962. return sock;
  963. }
  964. struct sock *netlink_getsockbyfd(int fd)
  965. {
  966. CLASS(fd, f)(fd);
  967. struct inode *inode;
  968. struct sock *sock;
  969. if (fd_empty(f))
  970. return ERR_PTR(-EBADF);
  971. inode = file_inode(fd_file(f));
  972. if (!S_ISSOCK(inode->i_mode))
  973. return ERR_PTR(-ENOTSOCK);
  974. sock = SOCKET_I(inode)->sk;
  975. if (sock->sk_family != AF_NETLINK)
  976. return ERR_PTR(-EINVAL);
  977. sock_hold(sock);
  978. return sock;
  979. }
  980. struct sk_buff *netlink_alloc_large_skb(unsigned int size, int broadcast)
  981. {
  982. size_t head_size = SKB_HEAD_ALIGN(size);
  983. struct sk_buff *skb;
  984. void *data;
  985. if (head_size <= PAGE_SIZE || broadcast)
  986. return alloc_skb(size, GFP_KERNEL);
  987. data = kvmalloc(head_size, GFP_KERNEL);
  988. if (!data)
  989. return NULL;
  990. skb = __build_skb(data, head_size);
  991. if (!skb)
  992. kvfree(data);
  993. else if (is_vmalloc_addr(data))
  994. skb->destructor = netlink_skb_destructor;
  995. return skb;
  996. }
  997. /*
  998. * Attach a skb to a netlink socket.
  999. * The caller must hold a reference to the destination socket. On error, the
  1000. * reference is dropped. The skb is not send to the destination, just all
  1001. * all error checks are performed and memory in the queue is reserved.
  1002. * Return values:
  1003. * < 0: error. skb freed, reference to sock dropped.
  1004. * 0: continue
  1005. * 1: repeat lookup - reference dropped while waiting for socket memory.
  1006. */
  1007. int netlink_attachskb(struct sock *sk, struct sk_buff *skb,
  1008. long *timeo, struct sock *ssk)
  1009. {
  1010. DECLARE_WAITQUEUE(wait, current);
  1011. struct netlink_sock *nlk;
  1012. unsigned int rmem;
  1013. nlk = nlk_sk(sk);
  1014. rmem = atomic_add_return(skb->truesize, &sk->sk_rmem_alloc);
  1015. if ((rmem == skb->truesize || rmem <= READ_ONCE(sk->sk_rcvbuf)) &&
  1016. !test_bit(NETLINK_S_CONGESTED, &nlk->state)) {
  1017. netlink_skb_set_owner_r(skb, sk);
  1018. return 0;
  1019. }
  1020. atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
  1021. if (!*timeo) {
  1022. if (!ssk || netlink_is_kernel(ssk))
  1023. netlink_overrun(sk);
  1024. sock_put(sk);
  1025. kfree_skb(skb);
  1026. return -EAGAIN;
  1027. }
  1028. __set_current_state(TASK_INTERRUPTIBLE);
  1029. add_wait_queue(&nlk->wait, &wait);
  1030. rmem = atomic_read(&sk->sk_rmem_alloc);
  1031. if (((rmem && rmem + skb->truesize > READ_ONCE(sk->sk_rcvbuf)) ||
  1032. test_bit(NETLINK_S_CONGESTED, &nlk->state)) &&
  1033. !sock_flag(sk, SOCK_DEAD))
  1034. *timeo = schedule_timeout(*timeo);
  1035. __set_current_state(TASK_RUNNING);
  1036. remove_wait_queue(&nlk->wait, &wait);
  1037. sock_put(sk);
  1038. if (signal_pending(current)) {
  1039. kfree_skb(skb);
  1040. return sock_intr_errno(*timeo);
  1041. }
  1042. return 1;
  1043. }
  1044. static int __netlink_sendskb(struct sock *sk, struct sk_buff *skb)
  1045. {
  1046. int len = skb->len;
  1047. netlink_deliver_tap(sock_net(sk), skb);
  1048. skb_queue_tail(&sk->sk_receive_queue, skb);
  1049. sk->sk_data_ready(sk);
  1050. return len;
  1051. }
  1052. int netlink_sendskb(struct sock *sk, struct sk_buff *skb)
  1053. {
  1054. int len = __netlink_sendskb(sk, skb);
  1055. sock_put(sk);
  1056. return len;
  1057. }
  1058. void netlink_detachskb(struct sock *sk, struct sk_buff *skb)
  1059. {
  1060. kfree_skb(skb);
  1061. sock_put(sk);
  1062. }
  1063. static struct sk_buff *netlink_trim(struct sk_buff *skb, gfp_t allocation)
  1064. {
  1065. int delta;
  1066. skb_assert_len(skb);
  1067. WARN_ON(skb->sk != NULL);
  1068. delta = skb->end - skb->tail;
  1069. if (is_vmalloc_addr(skb->head) || delta * 2 < skb->truesize)
  1070. return skb;
  1071. if (skb_shared(skb)) {
  1072. struct sk_buff *nskb = skb_clone(skb, allocation);
  1073. if (!nskb)
  1074. return skb;
  1075. consume_skb(skb);
  1076. skb = nskb;
  1077. }
  1078. pskb_expand_head(skb, 0, -delta,
  1079. (allocation & ~__GFP_DIRECT_RECLAIM) |
  1080. __GFP_NOWARN | __GFP_NORETRY);
  1081. return skb;
  1082. }
  1083. static int netlink_unicast_kernel(struct sock *sk, struct sk_buff *skb,
  1084. struct sock *ssk)
  1085. {
  1086. int ret;
  1087. struct netlink_sock *nlk = nlk_sk(sk);
  1088. ret = -ECONNREFUSED;
  1089. if (nlk->netlink_rcv != NULL) {
  1090. ret = skb->len;
  1091. atomic_add(skb->truesize, &sk->sk_rmem_alloc);
  1092. netlink_skb_set_owner_r(skb, sk);
  1093. NETLINK_CB(skb).sk = ssk;
  1094. netlink_deliver_tap_kernel(sk, ssk, skb);
  1095. nlk->netlink_rcv(skb);
  1096. consume_skb(skb);
  1097. } else {
  1098. kfree_skb(skb);
  1099. }
  1100. sock_put(sk);
  1101. return ret;
  1102. }
  1103. int netlink_unicast(struct sock *ssk, struct sk_buff *skb,
  1104. u32 portid, int nonblock)
  1105. {
  1106. struct sock *sk;
  1107. int err;
  1108. long timeo;
  1109. skb = netlink_trim(skb, gfp_any());
  1110. timeo = sock_sndtimeo(ssk, nonblock);
  1111. retry:
  1112. sk = netlink_getsockbyportid(ssk, portid);
  1113. if (IS_ERR(sk)) {
  1114. kfree_skb(skb);
  1115. return PTR_ERR(sk);
  1116. }
  1117. if (netlink_is_kernel(sk))
  1118. return netlink_unicast_kernel(sk, skb, ssk);
  1119. if (sk_filter(sk, skb)) {
  1120. err = skb->len;
  1121. kfree_skb(skb);
  1122. sock_put(sk);
  1123. return err;
  1124. }
  1125. err = netlink_attachskb(sk, skb, &timeo, ssk);
  1126. if (err == 1)
  1127. goto retry;
  1128. if (err)
  1129. return err;
  1130. return netlink_sendskb(sk, skb);
  1131. }
  1132. EXPORT_SYMBOL(netlink_unicast);
  1133. int netlink_has_listeners(struct sock *sk, unsigned int group)
  1134. {
  1135. int res = 0;
  1136. struct listeners *listeners;
  1137. BUG_ON(!netlink_is_kernel(sk));
  1138. rcu_read_lock();
  1139. listeners = rcu_dereference(nl_table[sk->sk_protocol].listeners);
  1140. if (listeners && group - 1 < nl_table[sk->sk_protocol].groups)
  1141. res = test_bit(group - 1, listeners->masks);
  1142. rcu_read_unlock();
  1143. return res;
  1144. }
  1145. EXPORT_SYMBOL_GPL(netlink_has_listeners);
  1146. bool netlink_strict_get_check(struct sk_buff *skb)
  1147. {
  1148. return nlk_test_bit(STRICT_CHK, NETLINK_CB(skb).sk);
  1149. }
  1150. EXPORT_SYMBOL_GPL(netlink_strict_get_check);
  1151. static int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
  1152. {
  1153. struct netlink_sock *nlk = nlk_sk(sk);
  1154. unsigned int rmem, rcvbuf;
  1155. rmem = atomic_add_return(skb->truesize, &sk->sk_rmem_alloc);
  1156. rcvbuf = READ_ONCE(sk->sk_rcvbuf);
  1157. if ((rmem == skb->truesize || rmem <= rcvbuf) &&
  1158. !test_bit(NETLINK_S_CONGESTED, &nlk->state)) {
  1159. netlink_skb_set_owner_r(skb, sk);
  1160. __netlink_sendskb(sk, skb);
  1161. return rmem > (rcvbuf >> 1);
  1162. }
  1163. atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
  1164. return -1;
  1165. }
  1166. struct netlink_broadcast_data {
  1167. struct sock *exclude_sk;
  1168. struct net *net;
  1169. u32 portid;
  1170. u32 group;
  1171. int failure;
  1172. int delivery_failure;
  1173. int congested;
  1174. int delivered;
  1175. gfp_t allocation;
  1176. struct sk_buff *skb, *skb2;
  1177. int (*tx_filter)(struct sock *dsk, struct sk_buff *skb, void *data);
  1178. void *tx_data;
  1179. };
  1180. static void do_one_broadcast(struct sock *sk,
  1181. struct netlink_broadcast_data *p)
  1182. {
  1183. struct netlink_sock *nlk = nlk_sk(sk);
  1184. int val;
  1185. if (p->exclude_sk == sk)
  1186. return;
  1187. if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
  1188. !test_bit(p->group - 1, nlk->groups))
  1189. return;
  1190. if (!net_eq(sock_net(sk), p->net)) {
  1191. if (!nlk_test_bit(LISTEN_ALL_NSID, sk))
  1192. return;
  1193. if (!peernet_has_id(sock_net(sk), p->net))
  1194. return;
  1195. if (!file_ns_capable(sk->sk_socket->file, p->net->user_ns,
  1196. CAP_NET_BROADCAST))
  1197. return;
  1198. }
  1199. if (p->failure) {
  1200. netlink_overrun(sk);
  1201. return;
  1202. }
  1203. sock_hold(sk);
  1204. if (p->skb2 == NULL) {
  1205. if (skb_shared(p->skb)) {
  1206. p->skb2 = skb_clone(p->skb, p->allocation);
  1207. } else {
  1208. p->skb2 = skb_get(p->skb);
  1209. /*
  1210. * skb ownership may have been set when
  1211. * delivered to a previous socket.
  1212. */
  1213. skb_orphan(p->skb2);
  1214. }
  1215. }
  1216. if (p->skb2 == NULL) {
  1217. netlink_overrun(sk);
  1218. /* Clone failed. Notify ALL listeners. */
  1219. p->failure = 1;
  1220. if (nlk_test_bit(BROADCAST_SEND_ERROR, sk))
  1221. p->delivery_failure = 1;
  1222. goto out;
  1223. }
  1224. if (p->tx_filter && p->tx_filter(sk, p->skb2, p->tx_data)) {
  1225. kfree_skb(p->skb2);
  1226. p->skb2 = NULL;
  1227. goto out;
  1228. }
  1229. if (sk_filter(sk, p->skb2)) {
  1230. kfree_skb(p->skb2);
  1231. p->skb2 = NULL;
  1232. goto out;
  1233. }
  1234. NETLINK_CB(p->skb2).nsid = peernet2id(sock_net(sk), p->net);
  1235. if (NETLINK_CB(p->skb2).nsid != NETNSA_NSID_NOT_ASSIGNED)
  1236. NETLINK_CB(p->skb2).nsid_is_set = true;
  1237. val = netlink_broadcast_deliver(sk, p->skb2);
  1238. if (val < 0) {
  1239. netlink_overrun(sk);
  1240. if (nlk_test_bit(BROADCAST_SEND_ERROR, sk))
  1241. p->delivery_failure = 1;
  1242. } else {
  1243. p->congested |= val;
  1244. p->delivered = 1;
  1245. p->skb2 = NULL;
  1246. }
  1247. out:
  1248. sock_put(sk);
  1249. }
  1250. int netlink_broadcast_filtered(struct sock *ssk, struct sk_buff *skb,
  1251. u32 portid,
  1252. u32 group, gfp_t allocation,
  1253. netlink_filter_fn filter,
  1254. void *filter_data)
  1255. {
  1256. struct net *net = sock_net(ssk);
  1257. struct netlink_broadcast_data info;
  1258. struct sock *sk;
  1259. skb = netlink_trim(skb, allocation);
  1260. info.exclude_sk = ssk;
  1261. info.net = net;
  1262. info.portid = portid;
  1263. info.group = group;
  1264. info.failure = 0;
  1265. info.delivery_failure = 0;
  1266. info.congested = 0;
  1267. info.delivered = 0;
  1268. info.allocation = allocation;
  1269. info.skb = skb;
  1270. info.skb2 = NULL;
  1271. info.tx_filter = filter;
  1272. info.tx_data = filter_data;
  1273. /* While we sleep in clone, do not allow to change socket list */
  1274. netlink_lock_table();
  1275. sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
  1276. do_one_broadcast(sk, &info);
  1277. consume_skb(skb);
  1278. netlink_unlock_table();
  1279. if (info.delivery_failure) {
  1280. kfree_skb(info.skb2);
  1281. return -ENOBUFS;
  1282. }
  1283. consume_skb(info.skb2);
  1284. if (info.delivered) {
  1285. if (info.congested && gfpflags_allow_blocking(allocation))
  1286. yield();
  1287. return 0;
  1288. }
  1289. return -ESRCH;
  1290. }
  1291. EXPORT_SYMBOL(netlink_broadcast_filtered);
  1292. int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 portid,
  1293. u32 group, gfp_t allocation)
  1294. {
  1295. return netlink_broadcast_filtered(ssk, skb, portid, group, allocation,
  1296. NULL, NULL);
  1297. }
  1298. EXPORT_SYMBOL(netlink_broadcast);
  1299. struct netlink_set_err_data {
  1300. struct sock *exclude_sk;
  1301. u32 portid;
  1302. u32 group;
  1303. int code;
  1304. };
  1305. static int do_one_set_err(struct sock *sk, struct netlink_set_err_data *p)
  1306. {
  1307. struct netlink_sock *nlk = nlk_sk(sk);
  1308. int ret = 0;
  1309. if (sk == p->exclude_sk)
  1310. goto out;
  1311. if (!net_eq(sock_net(sk), sock_net(p->exclude_sk)))
  1312. goto out;
  1313. if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
  1314. !test_bit(p->group - 1, nlk->groups))
  1315. goto out;
  1316. if (p->code == ENOBUFS && nlk_test_bit(RECV_NO_ENOBUFS, sk)) {
  1317. ret = 1;
  1318. goto out;
  1319. }
  1320. WRITE_ONCE(sk->sk_err, p->code);
  1321. sk_error_report(sk);
  1322. out:
  1323. return ret;
  1324. }
  1325. /**
  1326. * netlink_set_err - report error to broadcast listeners
  1327. * @ssk: the kernel netlink socket, as returned by netlink_kernel_create()
  1328. * @portid: the PORTID of a process that we want to skip (if any)
  1329. * @group: the broadcast group that will notice the error
  1330. * @code: error code, must be negative (as usual in kernelspace)
  1331. *
  1332. * This function returns the number of broadcast listeners that have set the
  1333. * NETLINK_NO_ENOBUFS socket option.
  1334. */
  1335. int netlink_set_err(struct sock *ssk, u32 portid, u32 group, int code)
  1336. {
  1337. struct netlink_set_err_data info;
  1338. unsigned long flags;
  1339. struct sock *sk;
  1340. int ret = 0;
  1341. info.exclude_sk = ssk;
  1342. info.portid = portid;
  1343. info.group = group;
  1344. /* sk->sk_err wants a positive error value */
  1345. info.code = -code;
  1346. read_lock_irqsave(&nl_table_lock, flags);
  1347. sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
  1348. ret += do_one_set_err(sk, &info);
  1349. read_unlock_irqrestore(&nl_table_lock, flags);
  1350. return ret;
  1351. }
  1352. EXPORT_SYMBOL(netlink_set_err);
  1353. /* must be called with netlink table grabbed */
  1354. static void netlink_update_socket_mc(struct netlink_sock *nlk,
  1355. unsigned int group,
  1356. int is_new)
  1357. {
  1358. int old, new = !!is_new, subscriptions;
  1359. old = test_bit(group - 1, nlk->groups);
  1360. subscriptions = nlk->subscriptions - old + new;
  1361. __assign_bit(group - 1, nlk->groups, new);
  1362. netlink_update_subscriptions(&nlk->sk, subscriptions);
  1363. netlink_update_listeners(&nlk->sk);
  1364. }
  1365. static int netlink_setsockopt(struct socket *sock, int level, int optname,
  1366. sockptr_t optval, unsigned int optlen)
  1367. {
  1368. struct sock *sk = sock->sk;
  1369. struct netlink_sock *nlk = nlk_sk(sk);
  1370. unsigned int val = 0;
  1371. int nr = -1;
  1372. if (level != SOL_NETLINK)
  1373. return -ENOPROTOOPT;
  1374. if (optlen >= sizeof(int) &&
  1375. copy_from_sockptr(&val, optval, sizeof(val)))
  1376. return -EFAULT;
  1377. switch (optname) {
  1378. case NETLINK_PKTINFO:
  1379. nr = NETLINK_F_RECV_PKTINFO;
  1380. break;
  1381. case NETLINK_ADD_MEMBERSHIP:
  1382. case NETLINK_DROP_MEMBERSHIP: {
  1383. int err;
  1384. if (!netlink_allowed(sock, NL_CFG_F_NONROOT_RECV))
  1385. return -EPERM;
  1386. err = netlink_realloc_groups(sk);
  1387. if (err)
  1388. return err;
  1389. if (!val || val - 1 >= nlk->ngroups)
  1390. return -EINVAL;
  1391. if (optname == NETLINK_ADD_MEMBERSHIP && nlk->netlink_bind) {
  1392. err = nlk->netlink_bind(sock_net(sk), val);
  1393. if (err)
  1394. return err;
  1395. }
  1396. netlink_table_grab();
  1397. netlink_update_socket_mc(nlk, val,
  1398. optname == NETLINK_ADD_MEMBERSHIP);
  1399. netlink_table_ungrab();
  1400. if (optname == NETLINK_DROP_MEMBERSHIP && nlk->netlink_unbind)
  1401. nlk->netlink_unbind(sock_net(sk), val);
  1402. break;
  1403. }
  1404. case NETLINK_BROADCAST_ERROR:
  1405. nr = NETLINK_F_BROADCAST_SEND_ERROR;
  1406. break;
  1407. case NETLINK_NO_ENOBUFS:
  1408. assign_bit(NETLINK_F_RECV_NO_ENOBUFS, &nlk->flags, val);
  1409. if (val) {
  1410. clear_bit(NETLINK_S_CONGESTED, &nlk->state);
  1411. wake_up_interruptible(&nlk->wait);
  1412. }
  1413. break;
  1414. case NETLINK_LISTEN_ALL_NSID:
  1415. if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_BROADCAST))
  1416. return -EPERM;
  1417. nr = NETLINK_F_LISTEN_ALL_NSID;
  1418. break;
  1419. case NETLINK_CAP_ACK:
  1420. nr = NETLINK_F_CAP_ACK;
  1421. break;
  1422. case NETLINK_EXT_ACK:
  1423. nr = NETLINK_F_EXT_ACK;
  1424. break;
  1425. case NETLINK_GET_STRICT_CHK:
  1426. nr = NETLINK_F_STRICT_CHK;
  1427. break;
  1428. default:
  1429. return -ENOPROTOOPT;
  1430. }
  1431. if (nr >= 0)
  1432. assign_bit(nr, &nlk->flags, val);
  1433. return 0;
  1434. }
  1435. static int netlink_getsockopt(struct socket *sock, int level, int optname,
  1436. char __user *optval, int __user *optlen)
  1437. {
  1438. struct sock *sk = sock->sk;
  1439. struct netlink_sock *nlk = nlk_sk(sk);
  1440. unsigned int flag;
  1441. int len, val;
  1442. if (level != SOL_NETLINK)
  1443. return -ENOPROTOOPT;
  1444. if (get_user(len, optlen))
  1445. return -EFAULT;
  1446. if (len < 0)
  1447. return -EINVAL;
  1448. switch (optname) {
  1449. case NETLINK_PKTINFO:
  1450. flag = NETLINK_F_RECV_PKTINFO;
  1451. break;
  1452. case NETLINK_BROADCAST_ERROR:
  1453. flag = NETLINK_F_BROADCAST_SEND_ERROR;
  1454. break;
  1455. case NETLINK_NO_ENOBUFS:
  1456. flag = NETLINK_F_RECV_NO_ENOBUFS;
  1457. break;
  1458. case NETLINK_LIST_MEMBERSHIPS: {
  1459. int pos, idx, shift, err = 0;
  1460. netlink_lock_table();
  1461. for (pos = 0; pos * 8 < nlk->ngroups; pos += sizeof(u32)) {
  1462. if (len - pos < sizeof(u32))
  1463. break;
  1464. idx = pos / sizeof(unsigned long);
  1465. shift = (pos % sizeof(unsigned long)) * 8;
  1466. if (put_user((u32)(nlk->groups[idx] >> shift),
  1467. (u32 __user *)(optval + pos))) {
  1468. err = -EFAULT;
  1469. break;
  1470. }
  1471. }
  1472. if (put_user(ALIGN(BITS_TO_BYTES(nlk->ngroups), sizeof(u32)), optlen))
  1473. err = -EFAULT;
  1474. netlink_unlock_table();
  1475. return err;
  1476. }
  1477. case NETLINK_LISTEN_ALL_NSID:
  1478. flag = NETLINK_F_LISTEN_ALL_NSID;
  1479. break;
  1480. case NETLINK_CAP_ACK:
  1481. flag = NETLINK_F_CAP_ACK;
  1482. break;
  1483. case NETLINK_EXT_ACK:
  1484. flag = NETLINK_F_EXT_ACK;
  1485. break;
  1486. case NETLINK_GET_STRICT_CHK:
  1487. flag = NETLINK_F_STRICT_CHK;
  1488. break;
  1489. default:
  1490. return -ENOPROTOOPT;
  1491. }
  1492. if (len < sizeof(int))
  1493. return -EINVAL;
  1494. len = sizeof(int);
  1495. val = test_bit(flag, &nlk->flags);
  1496. if (put_user(len, optlen) ||
  1497. copy_to_user(optval, &val, len))
  1498. return -EFAULT;
  1499. return 0;
  1500. }
  1501. static void netlink_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb)
  1502. {
  1503. struct nl_pktinfo info;
  1504. info.group = NETLINK_CB(skb).dst_group;
  1505. put_cmsg(msg, SOL_NETLINK, NETLINK_PKTINFO, sizeof(info), &info);
  1506. }
  1507. static void netlink_cmsg_listen_all_nsid(struct sock *sk, struct msghdr *msg,
  1508. struct sk_buff *skb)
  1509. {
  1510. if (!NETLINK_CB(skb).nsid_is_set)
  1511. return;
  1512. put_cmsg(msg, SOL_NETLINK, NETLINK_LISTEN_ALL_NSID, sizeof(int),
  1513. &NETLINK_CB(skb).nsid);
  1514. }
  1515. static int netlink_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
  1516. {
  1517. struct sock *sk = sock->sk;
  1518. struct netlink_sock *nlk = nlk_sk(sk);
  1519. DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
  1520. u32 dst_portid;
  1521. u32 dst_group;
  1522. struct sk_buff *skb;
  1523. int err;
  1524. struct scm_cookie scm;
  1525. u32 netlink_skb_flags = 0;
  1526. if (msg->msg_flags & MSG_OOB)
  1527. return -EOPNOTSUPP;
  1528. if (len == 0) {
  1529. pr_warn_once("Zero length message leads to an empty skb\n");
  1530. return -ENODATA;
  1531. }
  1532. err = scm_send(sock, msg, &scm, true);
  1533. if (err < 0)
  1534. return err;
  1535. if (msg->msg_namelen) {
  1536. err = -EINVAL;
  1537. if (msg->msg_namelen < sizeof(struct sockaddr_nl))
  1538. goto out;
  1539. if (addr->nl_family != AF_NETLINK)
  1540. goto out;
  1541. dst_portid = addr->nl_pid;
  1542. dst_group = ffs(addr->nl_groups);
  1543. err = -EPERM;
  1544. if ((dst_group || dst_portid) &&
  1545. !netlink_allowed(sock, NL_CFG_F_NONROOT_SEND))
  1546. goto out;
  1547. netlink_skb_flags |= NETLINK_SKB_DST;
  1548. } else {
  1549. /* Paired with WRITE_ONCE() in netlink_connect() */
  1550. dst_portid = READ_ONCE(nlk->dst_portid);
  1551. dst_group = READ_ONCE(nlk->dst_group);
  1552. }
  1553. /* Paired with WRITE_ONCE() in netlink_insert() */
  1554. if (!READ_ONCE(nlk->bound)) {
  1555. err = netlink_autobind(sock);
  1556. if (err)
  1557. goto out;
  1558. } else {
  1559. /* Ensure nlk is hashed and visible. */
  1560. smp_rmb();
  1561. }
  1562. err = -EMSGSIZE;
  1563. if (len > sk->sk_sndbuf - 32)
  1564. goto out;
  1565. err = -ENOBUFS;
  1566. skb = netlink_alloc_large_skb(len, dst_group);
  1567. if (skb == NULL)
  1568. goto out;
  1569. NETLINK_CB(skb).portid = nlk->portid;
  1570. NETLINK_CB(skb).dst_group = dst_group;
  1571. NETLINK_CB(skb).creds = scm.creds;
  1572. NETLINK_CB(skb).flags = netlink_skb_flags;
  1573. err = -EFAULT;
  1574. if (memcpy_from_msg(skb_put(skb, len), msg, len)) {
  1575. kfree_skb(skb);
  1576. goto out;
  1577. }
  1578. err = security_netlink_send(sk, skb);
  1579. if (err) {
  1580. kfree_skb(skb);
  1581. goto out;
  1582. }
  1583. if (dst_group) {
  1584. refcount_inc(&skb->users);
  1585. netlink_broadcast(sk, skb, dst_portid, dst_group, GFP_KERNEL);
  1586. }
  1587. err = netlink_unicast(sk, skb, dst_portid, msg->msg_flags & MSG_DONTWAIT);
  1588. out:
  1589. scm_destroy(&scm);
  1590. return err;
  1591. }
  1592. static int netlink_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
  1593. int flags)
  1594. {
  1595. struct scm_cookie scm;
  1596. struct sock *sk = sock->sk;
  1597. struct netlink_sock *nlk = nlk_sk(sk);
  1598. size_t copied, max_recvmsg_len;
  1599. struct sk_buff *skb, *data_skb;
  1600. int err, ret;
  1601. if (flags & MSG_OOB)
  1602. return -EOPNOTSUPP;
  1603. copied = 0;
  1604. skb = skb_recv_datagram(sk, flags, &err);
  1605. if (skb == NULL)
  1606. goto out;
  1607. data_skb = skb;
  1608. #ifdef CONFIG_COMPAT_NETLINK_MESSAGES
  1609. if (unlikely(skb_shinfo(skb)->frag_list)) {
  1610. /*
  1611. * If this skb has a frag_list, then here that means that we
  1612. * will have to use the frag_list skb's data for compat tasks
  1613. * and the regular skb's data for normal (non-compat) tasks.
  1614. *
  1615. * If we need to send the compat skb, assign it to the
  1616. * 'data_skb' variable so that it will be used below for data
  1617. * copying. We keep 'skb' for everything else, including
  1618. * freeing both later.
  1619. */
  1620. if (flags & MSG_CMSG_COMPAT)
  1621. data_skb = skb_shinfo(skb)->frag_list;
  1622. }
  1623. #endif
  1624. /* Record the max length of recvmsg() calls for future allocations */
  1625. max_recvmsg_len = max(READ_ONCE(nlk->max_recvmsg_len), len);
  1626. max_recvmsg_len = min_t(size_t, max_recvmsg_len,
  1627. SKB_WITH_OVERHEAD(32768));
  1628. WRITE_ONCE(nlk->max_recvmsg_len, max_recvmsg_len);
  1629. copied = data_skb->len;
  1630. if (len < copied) {
  1631. msg->msg_flags |= MSG_TRUNC;
  1632. copied = len;
  1633. }
  1634. err = skb_copy_datagram_msg(data_skb, 0, msg, copied);
  1635. if (msg->msg_name) {
  1636. DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
  1637. addr->nl_family = AF_NETLINK;
  1638. addr->nl_pad = 0;
  1639. addr->nl_pid = NETLINK_CB(skb).portid;
  1640. addr->nl_groups = netlink_group_mask(NETLINK_CB(skb).dst_group);
  1641. msg->msg_namelen = sizeof(*addr);
  1642. }
  1643. if (nlk_test_bit(RECV_PKTINFO, sk))
  1644. netlink_cmsg_recv_pktinfo(msg, skb);
  1645. if (nlk_test_bit(LISTEN_ALL_NSID, sk))
  1646. netlink_cmsg_listen_all_nsid(sk, msg, skb);
  1647. memset(&scm, 0, sizeof(scm));
  1648. scm.creds = *NETLINK_CREDS(skb);
  1649. if (flags & MSG_TRUNC)
  1650. copied = data_skb->len;
  1651. skb_free_datagram(sk, skb);
  1652. if (READ_ONCE(nlk->cb_running) &&
  1653. atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) {
  1654. ret = netlink_dump(sk, false);
  1655. if (ret) {
  1656. WRITE_ONCE(sk->sk_err, -ret);
  1657. sk_error_report(sk);
  1658. }
  1659. }
  1660. scm_recv(sock, msg, &scm, flags);
  1661. out:
  1662. netlink_rcv_wake(sk);
  1663. return err ? : copied;
  1664. }
  1665. static void netlink_data_ready(struct sock *sk)
  1666. {
  1667. BUG();
  1668. }
  1669. /*
  1670. * We export these functions to other modules. They provide a
  1671. * complete set of kernel non-blocking support for message
  1672. * queueing.
  1673. */
  1674. struct sock *
  1675. __netlink_kernel_create(struct net *net, int unit, struct module *module,
  1676. struct netlink_kernel_cfg *cfg)
  1677. {
  1678. struct socket *sock;
  1679. struct sock *sk;
  1680. struct netlink_sock *nlk;
  1681. struct listeners *listeners = NULL;
  1682. unsigned int groups;
  1683. BUG_ON(!nl_table);
  1684. if (unit < 0 || unit >= MAX_LINKS)
  1685. return NULL;
  1686. if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
  1687. return NULL;
  1688. if (__netlink_create(net, sock, unit, 1) < 0)
  1689. goto out_sock_release_nosk;
  1690. sk = sock->sk;
  1691. if (!cfg || cfg->groups < 32)
  1692. groups = 32;
  1693. else
  1694. groups = cfg->groups;
  1695. listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
  1696. if (!listeners)
  1697. goto out_sock_release;
  1698. sk->sk_data_ready = netlink_data_ready;
  1699. if (cfg && cfg->input)
  1700. nlk_sk(sk)->netlink_rcv = cfg->input;
  1701. if (netlink_insert(sk, 0))
  1702. goto out_sock_release;
  1703. nlk = nlk_sk(sk);
  1704. set_bit(NETLINK_F_KERNEL_SOCKET, &nlk->flags);
  1705. netlink_table_grab();
  1706. if (!nl_table[unit].registered) {
  1707. nl_table[unit].groups = groups;
  1708. rcu_assign_pointer(nl_table[unit].listeners, listeners);
  1709. nl_table[unit].module = module;
  1710. if (cfg) {
  1711. nl_table[unit].bind = cfg->bind;
  1712. nl_table[unit].unbind = cfg->unbind;
  1713. nl_table[unit].release = cfg->release;
  1714. nl_table[unit].flags = cfg->flags;
  1715. }
  1716. nl_table[unit].registered = 1;
  1717. } else {
  1718. kfree(listeners);
  1719. nl_table[unit].registered++;
  1720. }
  1721. netlink_table_ungrab();
  1722. return sk;
  1723. out_sock_release:
  1724. kfree(listeners);
  1725. netlink_kernel_release(sk);
  1726. return NULL;
  1727. out_sock_release_nosk:
  1728. sock_release(sock);
  1729. return NULL;
  1730. }
  1731. EXPORT_SYMBOL(__netlink_kernel_create);
  1732. void
  1733. netlink_kernel_release(struct sock *sk)
  1734. {
  1735. if (sk == NULL || sk->sk_socket == NULL)
  1736. return;
  1737. sock_release(sk->sk_socket);
  1738. }
  1739. EXPORT_SYMBOL(netlink_kernel_release);
  1740. int __netlink_change_ngroups(struct sock *sk, unsigned int groups)
  1741. {
  1742. struct listeners *new, *old;
  1743. struct netlink_table *tbl = &nl_table[sk->sk_protocol];
  1744. if (groups < 32)
  1745. groups = 32;
  1746. if (NLGRPSZ(tbl->groups) < NLGRPSZ(groups)) {
  1747. new = kzalloc(sizeof(*new) + NLGRPSZ(groups), GFP_ATOMIC);
  1748. if (!new)
  1749. return -ENOMEM;
  1750. old = nl_deref_protected(tbl->listeners);
  1751. memcpy(new->masks, old->masks, NLGRPSZ(tbl->groups));
  1752. rcu_assign_pointer(tbl->listeners, new);
  1753. kfree_rcu(old, rcu);
  1754. }
  1755. tbl->groups = groups;
  1756. return 0;
  1757. }
  1758. /**
  1759. * netlink_change_ngroups - change number of multicast groups
  1760. *
  1761. * This changes the number of multicast groups that are available
  1762. * on a certain netlink family. Note that it is not possible to
  1763. * change the number of groups to below 32. Also note that it does
  1764. * not implicitly call netlink_clear_multicast_users() when the
  1765. * number of groups is reduced.
  1766. *
  1767. * @sk: The kernel netlink socket, as returned by netlink_kernel_create().
  1768. * @groups: The new number of groups.
  1769. */
  1770. int netlink_change_ngroups(struct sock *sk, unsigned int groups)
  1771. {
  1772. int err;
  1773. netlink_table_grab();
  1774. err = __netlink_change_ngroups(sk, groups);
  1775. netlink_table_ungrab();
  1776. return err;
  1777. }
  1778. void __netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
  1779. {
  1780. struct sock *sk;
  1781. struct netlink_table *tbl = &nl_table[ksk->sk_protocol];
  1782. struct hlist_node *tmp;
  1783. sk_for_each_bound_safe(sk, tmp, &tbl->mc_list)
  1784. netlink_update_socket_mc(nlk_sk(sk), group, 0);
  1785. }
  1786. struct nlmsghdr *
  1787. __nlmsg_put(struct sk_buff *skb, u32 portid, u32 seq, int type, int len, int flags)
  1788. {
  1789. struct nlmsghdr *nlh;
  1790. int size = nlmsg_msg_size(len);
  1791. nlh = skb_put(skb, NLMSG_ALIGN(size));
  1792. nlh->nlmsg_type = type;
  1793. nlh->nlmsg_len = size;
  1794. nlh->nlmsg_flags = flags;
  1795. nlh->nlmsg_pid = portid;
  1796. nlh->nlmsg_seq = seq;
  1797. if (!__builtin_constant_p(size) || NLMSG_ALIGN(size) - size != 0)
  1798. memset(nlmsg_data(nlh) + len, 0, NLMSG_ALIGN(size) - size);
  1799. return nlh;
  1800. }
  1801. EXPORT_SYMBOL(__nlmsg_put);
  1802. static size_t
  1803. netlink_ack_tlv_len(struct netlink_sock *nlk, int err,
  1804. const struct netlink_ext_ack *extack)
  1805. {
  1806. size_t tlvlen;
  1807. if (!extack || !test_bit(NETLINK_F_EXT_ACK, &nlk->flags))
  1808. return 0;
  1809. tlvlen = 0;
  1810. if (extack->_msg)
  1811. tlvlen += nla_total_size(strlen(extack->_msg) + 1);
  1812. if (extack->cookie_len)
  1813. tlvlen += nla_total_size(extack->cookie_len);
  1814. /* Following attributes are only reported as error (not warning) */
  1815. if (!err)
  1816. return tlvlen;
  1817. if (extack->bad_attr)
  1818. tlvlen += nla_total_size(sizeof(u32));
  1819. if (extack->policy)
  1820. tlvlen += netlink_policy_dump_attr_size_estimate(extack->policy);
  1821. if (extack->miss_type)
  1822. tlvlen += nla_total_size(sizeof(u32));
  1823. if (extack->miss_nest)
  1824. tlvlen += nla_total_size(sizeof(u32));
  1825. return tlvlen;
  1826. }
  1827. static bool nlmsg_check_in_payload(const struct nlmsghdr *nlh, const void *addr)
  1828. {
  1829. return !WARN_ON(addr < nlmsg_data(nlh) ||
  1830. addr - (const void *) nlh >= nlh->nlmsg_len);
  1831. }
  1832. static void
  1833. netlink_ack_tlv_fill(struct sk_buff *skb, const struct nlmsghdr *nlh, int err,
  1834. const struct netlink_ext_ack *extack)
  1835. {
  1836. if (extack->_msg)
  1837. WARN_ON(nla_put_string(skb, NLMSGERR_ATTR_MSG, extack->_msg));
  1838. if (extack->cookie_len)
  1839. WARN_ON(nla_put(skb, NLMSGERR_ATTR_COOKIE,
  1840. extack->cookie_len, extack->cookie));
  1841. if (!err)
  1842. return;
  1843. if (extack->bad_attr && nlmsg_check_in_payload(nlh, extack->bad_attr))
  1844. WARN_ON(nla_put_u32(skb, NLMSGERR_ATTR_OFFS,
  1845. (u8 *)extack->bad_attr - (const u8 *)nlh));
  1846. if (extack->policy)
  1847. netlink_policy_dump_write_attr(skb, extack->policy,
  1848. NLMSGERR_ATTR_POLICY);
  1849. if (extack->miss_type)
  1850. WARN_ON(nla_put_u32(skb, NLMSGERR_ATTR_MISS_TYPE,
  1851. extack->miss_type));
  1852. if (extack->miss_nest && nlmsg_check_in_payload(nlh, extack->miss_nest))
  1853. WARN_ON(nla_put_u32(skb, NLMSGERR_ATTR_MISS_NEST,
  1854. (u8 *)extack->miss_nest - (const u8 *)nlh));
  1855. }
  1856. /*
  1857. * It looks a bit ugly.
  1858. * It would be better to create kernel thread.
  1859. */
  1860. static int netlink_dump_done(struct netlink_sock *nlk, struct sk_buff *skb,
  1861. struct netlink_callback *cb,
  1862. struct netlink_ext_ack *extack)
  1863. {
  1864. struct nlmsghdr *nlh;
  1865. size_t extack_len;
  1866. nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE, sizeof(nlk->dump_done_errno),
  1867. NLM_F_MULTI | cb->answer_flags);
  1868. if (WARN_ON(!nlh))
  1869. return -ENOBUFS;
  1870. nl_dump_check_consistent(cb, nlh);
  1871. memcpy(nlmsg_data(nlh), &nlk->dump_done_errno, sizeof(nlk->dump_done_errno));
  1872. extack_len = netlink_ack_tlv_len(nlk, nlk->dump_done_errno, extack);
  1873. if (extack_len) {
  1874. nlh->nlmsg_flags |= NLM_F_ACK_TLVS;
  1875. if (skb_tailroom(skb) >= extack_len) {
  1876. netlink_ack_tlv_fill(skb, cb->nlh,
  1877. nlk->dump_done_errno, extack);
  1878. nlmsg_end(skb, nlh);
  1879. }
  1880. }
  1881. return 0;
  1882. }
  1883. static int netlink_dump(struct sock *sk, bool lock_taken)
  1884. {
  1885. struct netlink_sock *nlk = nlk_sk(sk);
  1886. struct netlink_ext_ack extack = {};
  1887. struct netlink_callback *cb;
  1888. struct sk_buff *skb = NULL;
  1889. unsigned int rmem, rcvbuf;
  1890. size_t max_recvmsg_len;
  1891. struct module *module;
  1892. int err = -ENOBUFS;
  1893. int alloc_min_size;
  1894. int alloc_size;
  1895. if (!lock_taken)
  1896. mutex_lock(&nlk->nl_cb_mutex);
  1897. if (!nlk->cb_running) {
  1898. err = -EINVAL;
  1899. goto errout_skb;
  1900. }
  1901. /* NLMSG_GOODSIZE is small to avoid high order allocations being
  1902. * required, but it makes sense to _attempt_ a 32KiB allocation
  1903. * to reduce number of system calls on dump operations, if user
  1904. * ever provided a big enough buffer.
  1905. */
  1906. cb = &nlk->cb;
  1907. alloc_min_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE);
  1908. max_recvmsg_len = READ_ONCE(nlk->max_recvmsg_len);
  1909. if (alloc_min_size < max_recvmsg_len) {
  1910. alloc_size = max_recvmsg_len;
  1911. skb = alloc_skb(alloc_size,
  1912. (GFP_KERNEL & ~__GFP_DIRECT_RECLAIM) |
  1913. __GFP_NOWARN | __GFP_NORETRY);
  1914. }
  1915. if (!skb) {
  1916. alloc_size = alloc_min_size;
  1917. skb = alloc_skb(alloc_size, GFP_KERNEL);
  1918. }
  1919. if (!skb)
  1920. goto errout_skb;
  1921. rcvbuf = READ_ONCE(sk->sk_rcvbuf);
  1922. rmem = atomic_add_return(skb->truesize, &sk->sk_rmem_alloc);
  1923. if (rmem != skb->truesize && rmem >= rcvbuf) {
  1924. atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
  1925. goto errout_skb;
  1926. }
  1927. /* Trim skb to allocated size. User is expected to provide buffer as
  1928. * large as max(min_dump_alloc, 32KiB (max_recvmsg_len capped at
  1929. * netlink_recvmsg())). dump will pack as many smaller messages as
  1930. * could fit within the allocated skb. skb is typically allocated
  1931. * with larger space than required (could be as much as near 2x the
  1932. * requested size with align to next power of 2 approach). Allowing
  1933. * dump to use the excess space makes it difficult for a user to have a
  1934. * reasonable static buffer based on the expected largest dump of a
  1935. * single netdev. The outcome is MSG_TRUNC error.
  1936. */
  1937. skb_reserve(skb, skb_tailroom(skb) - alloc_size);
  1938. /* Make sure malicious BPF programs can not read unitialized memory
  1939. * from skb->head -> skb->data
  1940. */
  1941. skb_reset_network_header(skb);
  1942. skb_reset_mac_header(skb);
  1943. netlink_skb_set_owner_r(skb, sk);
  1944. if (nlk->dump_done_errno > 0) {
  1945. cb->extack = &extack;
  1946. nlk->dump_done_errno = cb->dump(skb, cb);
  1947. /* EMSGSIZE plus something already in the skb means
  1948. * that there's more to dump but current skb has filled up.
  1949. * If the callback really wants to return EMSGSIZE to user space
  1950. * it needs to do so again, on the next cb->dump() call,
  1951. * without putting data in the skb.
  1952. */
  1953. if (nlk->dump_done_errno == -EMSGSIZE && skb->len)
  1954. nlk->dump_done_errno = skb->len;
  1955. cb->extack = NULL;
  1956. }
  1957. if (nlk->dump_done_errno > 0 ||
  1958. skb_tailroom(skb) < nlmsg_total_size(sizeof(nlk->dump_done_errno))) {
  1959. mutex_unlock(&nlk->nl_cb_mutex);
  1960. if (sk_filter(sk, skb))
  1961. kfree_skb(skb);
  1962. else
  1963. __netlink_sendskb(sk, skb);
  1964. return 0;
  1965. }
  1966. if (netlink_dump_done(nlk, skb, cb, &extack))
  1967. goto errout_skb;
  1968. #ifdef CONFIG_COMPAT_NETLINK_MESSAGES
  1969. /* frag_list skb's data is used for compat tasks
  1970. * and the regular skb's data for normal (non-compat) tasks.
  1971. * See netlink_recvmsg().
  1972. */
  1973. if (unlikely(skb_shinfo(skb)->frag_list)) {
  1974. if (netlink_dump_done(nlk, skb_shinfo(skb)->frag_list, cb, &extack))
  1975. goto errout_skb;
  1976. }
  1977. #endif
  1978. if (sk_filter(sk, skb))
  1979. kfree_skb(skb);
  1980. else
  1981. __netlink_sendskb(sk, skb);
  1982. if (cb->done)
  1983. cb->done(cb);
  1984. WRITE_ONCE(nlk->cb_running, false);
  1985. module = cb->module;
  1986. skb = cb->skb;
  1987. mutex_unlock(&nlk->nl_cb_mutex);
  1988. module_put(module);
  1989. consume_skb(skb);
  1990. return 0;
  1991. errout_skb:
  1992. mutex_unlock(&nlk->nl_cb_mutex);
  1993. kfree_skb(skb);
  1994. return err;
  1995. }
  1996. int __netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
  1997. const struct nlmsghdr *nlh,
  1998. struct netlink_dump_control *control)
  1999. {
  2000. struct netlink_callback *cb;
  2001. struct netlink_sock *nlk;
  2002. struct sock *sk;
  2003. int ret;
  2004. refcount_inc(&skb->users);
  2005. sk = netlink_lookup(sock_net(ssk), ssk->sk_protocol, NETLINK_CB(skb).portid);
  2006. if (sk == NULL) {
  2007. ret = -ECONNREFUSED;
  2008. goto error_free;
  2009. }
  2010. nlk = nlk_sk(sk);
  2011. mutex_lock(&nlk->nl_cb_mutex);
  2012. /* A dump is in progress... */
  2013. if (nlk->cb_running) {
  2014. ret = -EBUSY;
  2015. goto error_unlock;
  2016. }
  2017. /* add reference of module which cb->dump belongs to */
  2018. if (!try_module_get(control->module)) {
  2019. ret = -EPROTONOSUPPORT;
  2020. goto error_unlock;
  2021. }
  2022. cb = &nlk->cb;
  2023. memset(cb, 0, sizeof(*cb));
  2024. cb->dump = control->dump;
  2025. cb->done = control->done;
  2026. cb->nlh = nlh;
  2027. cb->data = control->data;
  2028. cb->module = control->module;
  2029. cb->min_dump_alloc = control->min_dump_alloc;
  2030. cb->flags = control->flags;
  2031. cb->skb = skb;
  2032. cb->strict_check = nlk_test_bit(STRICT_CHK, NETLINK_CB(skb).sk);
  2033. if (control->start) {
  2034. cb->extack = control->extack;
  2035. ret = control->start(cb);
  2036. cb->extack = NULL;
  2037. if (ret)
  2038. goto error_put;
  2039. }
  2040. WRITE_ONCE(nlk->cb_running, true);
  2041. nlk->dump_done_errno = INT_MAX;
  2042. ret = netlink_dump(sk, true);
  2043. sock_put(sk);
  2044. if (ret)
  2045. return ret;
  2046. /* We successfully started a dump, by returning -EINTR we
  2047. * signal not to send ACK even if it was requested.
  2048. */
  2049. return -EINTR;
  2050. error_put:
  2051. module_put(control->module);
  2052. error_unlock:
  2053. sock_put(sk);
  2054. mutex_unlock(&nlk->nl_cb_mutex);
  2055. error_free:
  2056. kfree_skb(skb);
  2057. return ret;
  2058. }
  2059. EXPORT_SYMBOL(__netlink_dump_start);
  2060. void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err,
  2061. const struct netlink_ext_ack *extack)
  2062. {
  2063. struct sk_buff *skb;
  2064. struct nlmsghdr *rep;
  2065. struct nlmsgerr *errmsg;
  2066. size_t payload = sizeof(*errmsg);
  2067. struct netlink_sock *nlk = nlk_sk(NETLINK_CB(in_skb).sk);
  2068. unsigned int flags = 0;
  2069. size_t tlvlen;
  2070. /* Error messages get the original request appended, unless the user
  2071. * requests to cap the error message, and get extra error data if
  2072. * requested.
  2073. */
  2074. if (err && !test_bit(NETLINK_F_CAP_ACK, &nlk->flags))
  2075. payload += nlmsg_len(nlh);
  2076. else
  2077. flags |= NLM_F_CAPPED;
  2078. tlvlen = netlink_ack_tlv_len(nlk, err, extack);
  2079. if (tlvlen)
  2080. flags |= NLM_F_ACK_TLVS;
  2081. skb = nlmsg_new(payload + tlvlen, GFP_KERNEL);
  2082. if (!skb)
  2083. goto err_skb;
  2084. rep = nlmsg_put(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq,
  2085. NLMSG_ERROR, sizeof(*errmsg), flags);
  2086. if (!rep)
  2087. goto err_bad_put;
  2088. errmsg = nlmsg_data(rep);
  2089. errmsg->error = err;
  2090. errmsg->msg = *nlh;
  2091. if (!(flags & NLM_F_CAPPED)) {
  2092. if (!nlmsg_append(skb, nlmsg_len(nlh)))
  2093. goto err_bad_put;
  2094. memcpy(nlmsg_data(&errmsg->msg), nlmsg_data(nlh),
  2095. nlmsg_len(nlh));
  2096. }
  2097. if (tlvlen)
  2098. netlink_ack_tlv_fill(skb, nlh, err, extack);
  2099. nlmsg_end(skb, rep);
  2100. nlmsg_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).portid);
  2101. return;
  2102. err_bad_put:
  2103. nlmsg_free(skb);
  2104. err_skb:
  2105. WRITE_ONCE(NETLINK_CB(in_skb).sk->sk_err, ENOBUFS);
  2106. sk_error_report(NETLINK_CB(in_skb).sk);
  2107. }
  2108. EXPORT_SYMBOL(netlink_ack);
  2109. int netlink_rcv_skb(struct sk_buff *skb, int (*cb)(struct sk_buff *,
  2110. struct nlmsghdr *,
  2111. struct netlink_ext_ack *))
  2112. {
  2113. struct netlink_ext_ack extack;
  2114. struct nlmsghdr *nlh;
  2115. int err;
  2116. while (skb->len >= nlmsg_total_size(0)) {
  2117. int msglen;
  2118. memset(&extack, 0, sizeof(extack));
  2119. nlh = nlmsg_hdr(skb);
  2120. err = 0;
  2121. if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len)
  2122. return 0;
  2123. /* Only requests are handled by the kernel */
  2124. if (!(nlh->nlmsg_flags & NLM_F_REQUEST))
  2125. goto ack;
  2126. /* Skip control messages */
  2127. if (nlh->nlmsg_type < NLMSG_MIN_TYPE)
  2128. goto ack;
  2129. err = cb(skb, nlh, &extack);
  2130. if (err == -EINTR)
  2131. goto skip;
  2132. ack:
  2133. if (nlh->nlmsg_flags & NLM_F_ACK || err)
  2134. netlink_ack(skb, nlh, err, &extack);
  2135. skip:
  2136. msglen = NLMSG_ALIGN(nlh->nlmsg_len);
  2137. if (msglen > skb->len)
  2138. msglen = skb->len;
  2139. skb_pull(skb, msglen);
  2140. }
  2141. return 0;
  2142. }
  2143. EXPORT_SYMBOL(netlink_rcv_skb);
  2144. /**
  2145. * nlmsg_notify - send a notification netlink message
  2146. * @sk: netlink socket to use
  2147. * @skb: notification message
  2148. * @portid: destination netlink portid for reports or 0
  2149. * @group: destination multicast group or 0
  2150. * @report: 1 to report back, 0 to disable
  2151. * @flags: allocation flags
  2152. */
  2153. int nlmsg_notify(struct sock *sk, struct sk_buff *skb, u32 portid,
  2154. unsigned int group, int report, gfp_t flags)
  2155. {
  2156. int err = 0;
  2157. if (group) {
  2158. int exclude_portid = 0;
  2159. if (report) {
  2160. refcount_inc(&skb->users);
  2161. exclude_portid = portid;
  2162. }
  2163. /* errors reported via destination sk->sk_err, but propagate
  2164. * delivery errors if NETLINK_BROADCAST_ERROR flag is set */
  2165. err = nlmsg_multicast(sk, skb, exclude_portid, group, flags);
  2166. if (err == -ESRCH)
  2167. err = 0;
  2168. }
  2169. if (report) {
  2170. int err2;
  2171. err2 = nlmsg_unicast(sk, skb, portid);
  2172. if (!err)
  2173. err = err2;
  2174. }
  2175. return err;
  2176. }
  2177. EXPORT_SYMBOL(nlmsg_notify);
  2178. #ifdef CONFIG_PROC_FS
  2179. struct nl_seq_iter {
  2180. struct seq_net_private p;
  2181. struct rhashtable_iter hti;
  2182. int link;
  2183. };
  2184. static void netlink_walk_start(struct nl_seq_iter *iter)
  2185. {
  2186. rhashtable_walk_enter(&nl_table[iter->link].hash, &iter->hti);
  2187. rhashtable_walk_start(&iter->hti);
  2188. }
  2189. static void netlink_walk_stop(struct nl_seq_iter *iter)
  2190. {
  2191. rhashtable_walk_stop(&iter->hti);
  2192. rhashtable_walk_exit(&iter->hti);
  2193. }
  2194. static void *__netlink_seq_next(struct seq_file *seq)
  2195. {
  2196. struct nl_seq_iter *iter = seq->private;
  2197. struct netlink_sock *nlk;
  2198. do {
  2199. for (;;) {
  2200. nlk = rhashtable_walk_next(&iter->hti);
  2201. if (IS_ERR(nlk)) {
  2202. if (PTR_ERR(nlk) == -EAGAIN)
  2203. continue;
  2204. return nlk;
  2205. }
  2206. if (nlk)
  2207. break;
  2208. netlink_walk_stop(iter);
  2209. if (++iter->link >= MAX_LINKS)
  2210. return NULL;
  2211. netlink_walk_start(iter);
  2212. }
  2213. } while (sock_net(&nlk->sk) != seq_file_net(seq));
  2214. return nlk;
  2215. }
  2216. static void *netlink_seq_start(struct seq_file *seq, loff_t *posp)
  2217. __acquires(RCU)
  2218. {
  2219. struct nl_seq_iter *iter = seq->private;
  2220. void *obj = SEQ_START_TOKEN;
  2221. loff_t pos;
  2222. iter->link = 0;
  2223. netlink_walk_start(iter);
  2224. for (pos = *posp; pos && obj && !IS_ERR(obj); pos--)
  2225. obj = __netlink_seq_next(seq);
  2226. return obj;
  2227. }
  2228. static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
  2229. {
  2230. ++*pos;
  2231. return __netlink_seq_next(seq);
  2232. }
  2233. static void netlink_native_seq_stop(struct seq_file *seq, void *v)
  2234. {
  2235. struct nl_seq_iter *iter = seq->private;
  2236. if (iter->link >= MAX_LINKS)
  2237. return;
  2238. netlink_walk_stop(iter);
  2239. }
  2240. static int netlink_native_seq_show(struct seq_file *seq, void *v)
  2241. {
  2242. if (v == SEQ_START_TOKEN) {
  2243. seq_puts(seq,
  2244. "sk Eth Pid Groups "
  2245. "Rmem Wmem Dump Locks Drops Inode\n");
  2246. } else {
  2247. struct sock *s = v;
  2248. struct netlink_sock *nlk = nlk_sk(s);
  2249. seq_printf(seq, "%pK %-3d %-10u %08x %-8d %-8d %-5d %-8d %-8u %-8lu\n",
  2250. s,
  2251. s->sk_protocol,
  2252. nlk->portid,
  2253. nlk->groups ? (u32)nlk->groups[0] : 0,
  2254. sk_rmem_alloc_get(s),
  2255. sk_wmem_alloc_get(s),
  2256. READ_ONCE(nlk->cb_running),
  2257. refcount_read(&s->sk_refcnt),
  2258. sk_drops_read(s),
  2259. sock_i_ino(s)
  2260. );
  2261. }
  2262. return 0;
  2263. }
  2264. #ifdef CONFIG_BPF_SYSCALL
  2265. struct bpf_iter__netlink {
  2266. __bpf_md_ptr(struct bpf_iter_meta *, meta);
  2267. __bpf_md_ptr(struct netlink_sock *, sk);
  2268. };
  2269. DEFINE_BPF_ITER_FUNC(netlink, struct bpf_iter_meta *meta, struct netlink_sock *sk)
  2270. static int netlink_prog_seq_show(struct bpf_prog *prog,
  2271. struct bpf_iter_meta *meta,
  2272. void *v)
  2273. {
  2274. struct bpf_iter__netlink ctx;
  2275. meta->seq_num--; /* skip SEQ_START_TOKEN */
  2276. ctx.meta = meta;
  2277. ctx.sk = nlk_sk((struct sock *)v);
  2278. return bpf_iter_run_prog(prog, &ctx);
  2279. }
  2280. static int netlink_seq_show(struct seq_file *seq, void *v)
  2281. {
  2282. struct bpf_iter_meta meta;
  2283. struct bpf_prog *prog;
  2284. meta.seq = seq;
  2285. prog = bpf_iter_get_info(&meta, false);
  2286. if (!prog)
  2287. return netlink_native_seq_show(seq, v);
  2288. if (v != SEQ_START_TOKEN)
  2289. return netlink_prog_seq_show(prog, &meta, v);
  2290. return 0;
  2291. }
  2292. static void netlink_seq_stop(struct seq_file *seq, void *v)
  2293. {
  2294. struct bpf_iter_meta meta;
  2295. struct bpf_prog *prog;
  2296. if (!v) {
  2297. meta.seq = seq;
  2298. prog = bpf_iter_get_info(&meta, true);
  2299. if (prog)
  2300. (void)netlink_prog_seq_show(prog, &meta, v);
  2301. }
  2302. netlink_native_seq_stop(seq, v);
  2303. }
  2304. #else
  2305. static int netlink_seq_show(struct seq_file *seq, void *v)
  2306. {
  2307. return netlink_native_seq_show(seq, v);
  2308. }
  2309. static void netlink_seq_stop(struct seq_file *seq, void *v)
  2310. {
  2311. netlink_native_seq_stop(seq, v);
  2312. }
  2313. #endif
  2314. static const struct seq_operations netlink_seq_ops = {
  2315. .start = netlink_seq_start,
  2316. .next = netlink_seq_next,
  2317. .stop = netlink_seq_stop,
  2318. .show = netlink_seq_show,
  2319. };
  2320. #endif
  2321. int netlink_register_notifier(struct notifier_block *nb)
  2322. {
  2323. return blocking_notifier_chain_register(&netlink_chain, nb);
  2324. }
  2325. EXPORT_SYMBOL(netlink_register_notifier);
  2326. int netlink_unregister_notifier(struct notifier_block *nb)
  2327. {
  2328. return blocking_notifier_chain_unregister(&netlink_chain, nb);
  2329. }
  2330. EXPORT_SYMBOL(netlink_unregister_notifier);
  2331. static const struct proto_ops netlink_ops = {
  2332. .family = PF_NETLINK,
  2333. .owner = THIS_MODULE,
  2334. .release = netlink_release,
  2335. .bind = netlink_bind,
  2336. .connect = netlink_connect,
  2337. .socketpair = sock_no_socketpair,
  2338. .accept = sock_no_accept,
  2339. .getname = netlink_getname,
  2340. .poll = datagram_poll,
  2341. .ioctl = netlink_ioctl,
  2342. .listen = sock_no_listen,
  2343. .shutdown = sock_no_shutdown,
  2344. .setsockopt = netlink_setsockopt,
  2345. .getsockopt = netlink_getsockopt,
  2346. .sendmsg = netlink_sendmsg,
  2347. .recvmsg = netlink_recvmsg,
  2348. .mmap = sock_no_mmap,
  2349. };
  2350. static const struct net_proto_family netlink_family_ops = {
  2351. .family = PF_NETLINK,
  2352. .create = netlink_create,
  2353. .owner = THIS_MODULE, /* for consistency 8) */
  2354. };
  2355. static int __net_init netlink_net_init(struct net *net)
  2356. {
  2357. #ifdef CONFIG_PROC_FS
  2358. if (!proc_create_net("netlink", 0, net->proc_net, &netlink_seq_ops,
  2359. sizeof(struct nl_seq_iter)))
  2360. return -ENOMEM;
  2361. #endif
  2362. return 0;
  2363. }
  2364. static void __net_exit netlink_net_exit(struct net *net)
  2365. {
  2366. #ifdef CONFIG_PROC_FS
  2367. remove_proc_entry("netlink", net->proc_net);
  2368. #endif
  2369. }
  2370. static void __init netlink_add_usersock_entry(void)
  2371. {
  2372. struct listeners *listeners;
  2373. int groups = 32;
  2374. listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
  2375. if (!listeners)
  2376. panic("netlink_add_usersock_entry: Cannot allocate listeners\n");
  2377. netlink_table_grab();
  2378. nl_table[NETLINK_USERSOCK].groups = groups;
  2379. rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners);
  2380. nl_table[NETLINK_USERSOCK].module = THIS_MODULE;
  2381. nl_table[NETLINK_USERSOCK].registered = 1;
  2382. nl_table[NETLINK_USERSOCK].flags = NL_CFG_F_NONROOT_SEND;
  2383. netlink_table_ungrab();
  2384. }
  2385. static struct pernet_operations __net_initdata netlink_net_ops = {
  2386. .init = netlink_net_init,
  2387. .exit = netlink_net_exit,
  2388. };
  2389. static inline u32 netlink_hash(const void *data, u32 len, u32 seed)
  2390. {
  2391. const struct netlink_sock *nlk = data;
  2392. struct netlink_compare_arg arg;
  2393. netlink_compare_arg_init(&arg, sock_net(&nlk->sk), nlk->portid);
  2394. return jhash2((u32 *)&arg, netlink_compare_arg_len / sizeof(u32), seed);
  2395. }
  2396. static const struct rhashtable_params netlink_rhashtable_params = {
  2397. .head_offset = offsetof(struct netlink_sock, node),
  2398. .key_len = netlink_compare_arg_len,
  2399. .obj_hashfn = netlink_hash,
  2400. .obj_cmpfn = netlink_compare,
  2401. .automatic_shrinking = true,
  2402. };
  2403. #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
  2404. BTF_ID_LIST_SINGLE(btf_netlink_sock_id, struct, netlink_sock)
  2405. static const struct bpf_iter_seq_info netlink_seq_info = {
  2406. .seq_ops = &netlink_seq_ops,
  2407. .init_seq_private = bpf_iter_init_seq_net,
  2408. .fini_seq_private = bpf_iter_fini_seq_net,
  2409. .seq_priv_size = sizeof(struct nl_seq_iter),
  2410. };
  2411. static struct bpf_iter_reg netlink_reg_info = {
  2412. .target = "netlink",
  2413. .ctx_arg_info_size = 1,
  2414. .ctx_arg_info = {
  2415. { offsetof(struct bpf_iter__netlink, sk),
  2416. PTR_TO_BTF_ID_OR_NULL },
  2417. },
  2418. .seq_info = &netlink_seq_info,
  2419. };
  2420. static int __init bpf_iter_register(void)
  2421. {
  2422. netlink_reg_info.ctx_arg_info[0].btf_id = *btf_netlink_sock_id;
  2423. return bpf_iter_reg_target(&netlink_reg_info);
  2424. }
  2425. #endif
  2426. static int __init netlink_proto_init(void)
  2427. {
  2428. int i;
  2429. int err = proto_register(&netlink_proto, 0);
  2430. if (err != 0)
  2431. goto out;
  2432. #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
  2433. err = bpf_iter_register();
  2434. if (err)
  2435. goto out;
  2436. #endif
  2437. BUILD_BUG_ON(sizeof(struct netlink_skb_parms) > sizeof_field(struct sk_buff, cb));
  2438. nl_table = kzalloc_objs(*nl_table, MAX_LINKS);
  2439. if (!nl_table)
  2440. goto panic;
  2441. for (i = 0; i < MAX_LINKS; i++) {
  2442. if (rhashtable_init(&nl_table[i].hash,
  2443. &netlink_rhashtable_params) < 0)
  2444. goto panic;
  2445. }
  2446. netlink_add_usersock_entry();
  2447. sock_register(&netlink_family_ops);
  2448. register_pernet_subsys(&netlink_net_ops);
  2449. register_pernet_subsys(&netlink_tap_net_ops);
  2450. /* The netlink device handler may be needed early. */
  2451. rtnetlink_init();
  2452. out:
  2453. return err;
  2454. panic:
  2455. panic("netlink_init: Cannot allocate nl_table\n");
  2456. }
  2457. core_initcall(netlink_proto_init);