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. atomic_inc(&sk->sk_drops);
  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. WARN_ON(refcount_read(&sk->sk_refcnt) == 1);
  497. __sock_put(sk);
  498. }
  499. netlink_table_grab();
  500. if (nlk_sk(sk)->subscriptions) {
  501. __sk_del_bind_node(sk);
  502. netlink_update_listeners(sk);
  503. }
  504. if (sk->sk_protocol == NETLINK_GENERIC)
  505. atomic_inc(&genl_sk_destructing_cnt);
  506. netlink_table_ungrab();
  507. }
  508. static struct proto netlink_proto = {
  509. .name = "NETLINK",
  510. .owner = THIS_MODULE,
  511. .obj_size = sizeof(struct netlink_sock),
  512. };
  513. static int __netlink_create(struct net *net, struct socket *sock,
  514. int protocol, int kern)
  515. {
  516. struct sock *sk;
  517. struct netlink_sock *nlk;
  518. sock->ops = &netlink_ops;
  519. sk = sk_alloc(net, PF_NETLINK, GFP_KERNEL, &netlink_proto, kern);
  520. if (!sk)
  521. return -ENOMEM;
  522. sock_init_data(sock, sk);
  523. nlk = nlk_sk(sk);
  524. mutex_init(&nlk->nl_cb_mutex);
  525. lockdep_set_class_and_name(&nlk->nl_cb_mutex,
  526. nlk_cb_mutex_keys + protocol,
  527. nlk_cb_mutex_key_strings[protocol]);
  528. init_waitqueue_head(&nlk->wait);
  529. sk->sk_destruct = netlink_sock_destruct;
  530. sk->sk_protocol = protocol;
  531. return 0;
  532. }
  533. static int netlink_create(struct net *net, struct socket *sock, int protocol,
  534. int kern)
  535. {
  536. struct module *module = NULL;
  537. struct netlink_sock *nlk;
  538. int (*bind)(struct net *net, int group);
  539. void (*unbind)(struct net *net, int group);
  540. void (*release)(struct sock *sock, unsigned long *groups);
  541. int err = 0;
  542. sock->state = SS_UNCONNECTED;
  543. if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
  544. return -ESOCKTNOSUPPORT;
  545. if (protocol < 0 || protocol >= MAX_LINKS)
  546. return -EPROTONOSUPPORT;
  547. protocol = array_index_nospec(protocol, MAX_LINKS);
  548. netlink_lock_table();
  549. #ifdef CONFIG_MODULES
  550. if (!nl_table[protocol].registered) {
  551. netlink_unlock_table();
  552. request_module("net-pf-%d-proto-%d", PF_NETLINK, protocol);
  553. netlink_lock_table();
  554. }
  555. #endif
  556. if (nl_table[protocol].registered &&
  557. try_module_get(nl_table[protocol].module))
  558. module = nl_table[protocol].module;
  559. else
  560. err = -EPROTONOSUPPORT;
  561. bind = nl_table[protocol].bind;
  562. unbind = nl_table[protocol].unbind;
  563. release = nl_table[protocol].release;
  564. netlink_unlock_table();
  565. if (err < 0)
  566. goto out;
  567. err = __netlink_create(net, sock, protocol, kern);
  568. if (err < 0)
  569. goto out_module;
  570. sock_prot_inuse_add(net, &netlink_proto, 1);
  571. nlk = nlk_sk(sock->sk);
  572. nlk->module = module;
  573. nlk->netlink_bind = bind;
  574. nlk->netlink_unbind = unbind;
  575. nlk->netlink_release = release;
  576. out:
  577. return err;
  578. out_module:
  579. module_put(module);
  580. goto out;
  581. }
  582. static void deferred_put_nlk_sk(struct rcu_head *head)
  583. {
  584. struct netlink_sock *nlk = container_of(head, struct netlink_sock, rcu);
  585. struct sock *sk = &nlk->sk;
  586. kfree(nlk->groups);
  587. nlk->groups = NULL;
  588. if (!refcount_dec_and_test(&sk->sk_refcnt))
  589. return;
  590. sk_free(sk);
  591. }
  592. static int netlink_release(struct socket *sock)
  593. {
  594. struct sock *sk = sock->sk;
  595. struct netlink_sock *nlk;
  596. if (!sk)
  597. return 0;
  598. netlink_remove(sk);
  599. sock_orphan(sk);
  600. nlk = nlk_sk(sk);
  601. /*
  602. * OK. Socket is unlinked, any packets that arrive now
  603. * will be purged.
  604. */
  605. if (nlk->netlink_release)
  606. nlk->netlink_release(sk, nlk->groups);
  607. /* must not acquire netlink_table_lock in any way again before unbind
  608. * and notifying genetlink is done as otherwise it might deadlock
  609. */
  610. if (nlk->netlink_unbind) {
  611. int i;
  612. for (i = 0; i < nlk->ngroups; i++)
  613. if (test_bit(i, nlk->groups))
  614. nlk->netlink_unbind(sock_net(sk), i + 1);
  615. }
  616. if (sk->sk_protocol == NETLINK_GENERIC &&
  617. atomic_dec_return(&genl_sk_destructing_cnt) == 0)
  618. wake_up(&genl_sk_destructing_waitq);
  619. sock->sk = NULL;
  620. wake_up_interruptible_all(&nlk->wait);
  621. skb_queue_purge(&sk->sk_write_queue);
  622. if (nlk->portid && nlk->bound) {
  623. struct netlink_notify n = {
  624. .net = sock_net(sk),
  625. .protocol = sk->sk_protocol,
  626. .portid = nlk->portid,
  627. };
  628. blocking_notifier_call_chain(&netlink_chain,
  629. NETLINK_URELEASE, &n);
  630. }
  631. /* Terminate any outstanding dump */
  632. if (nlk->cb_running) {
  633. if (nlk->cb.done)
  634. nlk->cb.done(&nlk->cb);
  635. module_put(nlk->cb.module);
  636. kfree_skb(nlk->cb.skb);
  637. }
  638. module_put(nlk->module);
  639. if (netlink_is_kernel(sk)) {
  640. netlink_table_grab();
  641. BUG_ON(nl_table[sk->sk_protocol].registered == 0);
  642. if (--nl_table[sk->sk_protocol].registered == 0) {
  643. struct listeners *old;
  644. old = nl_deref_protected(nl_table[sk->sk_protocol].listeners);
  645. RCU_INIT_POINTER(nl_table[sk->sk_protocol].listeners, NULL);
  646. kfree_rcu(old, rcu);
  647. nl_table[sk->sk_protocol].module = NULL;
  648. nl_table[sk->sk_protocol].bind = NULL;
  649. nl_table[sk->sk_protocol].unbind = NULL;
  650. nl_table[sk->sk_protocol].flags = 0;
  651. nl_table[sk->sk_protocol].registered = 0;
  652. }
  653. netlink_table_ungrab();
  654. }
  655. sock_prot_inuse_add(sock_net(sk), &netlink_proto, -1);
  656. call_rcu(&nlk->rcu, deferred_put_nlk_sk);
  657. return 0;
  658. }
  659. static int netlink_autobind(struct socket *sock)
  660. {
  661. struct sock *sk = sock->sk;
  662. struct net *net = sock_net(sk);
  663. struct netlink_table *table = &nl_table[sk->sk_protocol];
  664. s32 portid = task_tgid_vnr(current);
  665. int err;
  666. s32 rover = -4096;
  667. bool ok;
  668. retry:
  669. cond_resched();
  670. rcu_read_lock();
  671. ok = !__netlink_lookup(table, portid, net);
  672. rcu_read_unlock();
  673. if (!ok) {
  674. /* Bind collision, search negative portid values. */
  675. if (rover == -4096)
  676. /* rover will be in range [S32_MIN, -4097] */
  677. rover = S32_MIN + get_random_u32_below(-4096 - S32_MIN);
  678. else if (rover >= -4096)
  679. rover = -4097;
  680. portid = rover--;
  681. goto retry;
  682. }
  683. err = netlink_insert(sk, portid);
  684. if (err == -EADDRINUSE)
  685. goto retry;
  686. /* If 2 threads race to autobind, that is fine. */
  687. if (err == -EBUSY)
  688. err = 0;
  689. return err;
  690. }
  691. /**
  692. * __netlink_ns_capable - General netlink message capability test
  693. * @nsp: NETLINK_CB of the socket buffer holding a netlink command from userspace.
  694. * @user_ns: The user namespace of the capability to use
  695. * @cap: The capability to use
  696. *
  697. * Test to see if the opener of the socket we received the message
  698. * from had when the netlink socket was created and the sender of the
  699. * message has the capability @cap in the user namespace @user_ns.
  700. */
  701. bool __netlink_ns_capable(const struct netlink_skb_parms *nsp,
  702. struct user_namespace *user_ns, int cap)
  703. {
  704. return ((nsp->flags & NETLINK_SKB_DST) ||
  705. file_ns_capable(nsp->sk->sk_socket->file, user_ns, cap)) &&
  706. ns_capable(user_ns, cap);
  707. }
  708. EXPORT_SYMBOL(__netlink_ns_capable);
  709. /**
  710. * netlink_ns_capable - General netlink message capability test
  711. * @skb: socket buffer holding a netlink command from userspace
  712. * @user_ns: The user namespace of the capability to use
  713. * @cap: The capability to use
  714. *
  715. * Test to see if the opener of the socket we received the message
  716. * from had when the netlink socket was created and the sender of the
  717. * message has the capability @cap in the user namespace @user_ns.
  718. */
  719. bool netlink_ns_capable(const struct sk_buff *skb,
  720. struct user_namespace *user_ns, int cap)
  721. {
  722. return __netlink_ns_capable(&NETLINK_CB(skb), user_ns, cap);
  723. }
  724. EXPORT_SYMBOL(netlink_ns_capable);
  725. /**
  726. * netlink_capable - Netlink global message capability test
  727. * @skb: socket buffer holding a netlink command from userspace
  728. * @cap: The capability to use
  729. *
  730. * Test to see if the opener of the socket we received the message
  731. * from had when the netlink socket was created and the sender of the
  732. * message has the capability @cap in all user namespaces.
  733. */
  734. bool netlink_capable(const struct sk_buff *skb, int cap)
  735. {
  736. return netlink_ns_capable(skb, &init_user_ns, cap);
  737. }
  738. EXPORT_SYMBOL(netlink_capable);
  739. /**
  740. * netlink_net_capable - Netlink network namespace message capability test
  741. * @skb: socket buffer holding a netlink command from userspace
  742. * @cap: The capability to use
  743. *
  744. * Test to see if the opener of the socket we received the message
  745. * from had when the netlink socket was created and the sender of the
  746. * message has the capability @cap over the network namespace of
  747. * the socket we received the message from.
  748. */
  749. bool netlink_net_capable(const struct sk_buff *skb, int cap)
  750. {
  751. return netlink_ns_capable(skb, sock_net(skb->sk)->user_ns, cap);
  752. }
  753. EXPORT_SYMBOL(netlink_net_capable);
  754. static inline int netlink_allowed(const struct socket *sock, unsigned int flag)
  755. {
  756. return (nl_table[sock->sk->sk_protocol].flags & flag) ||
  757. ns_capable(sock_net(sock->sk)->user_ns, CAP_NET_ADMIN);
  758. }
  759. static void
  760. netlink_update_subscriptions(struct sock *sk, unsigned int subscriptions)
  761. {
  762. struct netlink_sock *nlk = nlk_sk(sk);
  763. if (nlk->subscriptions && !subscriptions)
  764. __sk_del_bind_node(sk);
  765. else if (!nlk->subscriptions && subscriptions)
  766. sk_add_bind_node(sk, &nl_table[sk->sk_protocol].mc_list);
  767. nlk->subscriptions = subscriptions;
  768. }
  769. static int netlink_realloc_groups(struct sock *sk)
  770. {
  771. struct netlink_sock *nlk = nlk_sk(sk);
  772. unsigned int groups;
  773. unsigned long *new_groups;
  774. int err = 0;
  775. netlink_table_grab();
  776. groups = nl_table[sk->sk_protocol].groups;
  777. if (!nl_table[sk->sk_protocol].registered) {
  778. err = -ENOENT;
  779. goto out_unlock;
  780. }
  781. if (nlk->ngroups >= groups)
  782. goto out_unlock;
  783. new_groups = krealloc(nlk->groups, NLGRPSZ(groups), GFP_ATOMIC);
  784. if (new_groups == NULL) {
  785. err = -ENOMEM;
  786. goto out_unlock;
  787. }
  788. memset((char *)new_groups + NLGRPSZ(nlk->ngroups), 0,
  789. NLGRPSZ(groups) - NLGRPSZ(nlk->ngroups));
  790. nlk->groups = new_groups;
  791. nlk->ngroups = groups;
  792. out_unlock:
  793. netlink_table_ungrab();
  794. return err;
  795. }
  796. static void netlink_undo_bind(int group, long unsigned int groups,
  797. struct sock *sk)
  798. {
  799. struct netlink_sock *nlk = nlk_sk(sk);
  800. int undo;
  801. if (!nlk->netlink_unbind)
  802. return;
  803. for (undo = 0; undo < group; undo++)
  804. if (test_bit(undo, &groups))
  805. nlk->netlink_unbind(sock_net(sk), undo + 1);
  806. }
  807. static int netlink_bind(struct socket *sock, struct sockaddr *addr,
  808. int addr_len)
  809. {
  810. struct sock *sk = sock->sk;
  811. struct net *net = sock_net(sk);
  812. struct netlink_sock *nlk = nlk_sk(sk);
  813. struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
  814. int err = 0;
  815. unsigned long groups;
  816. bool bound;
  817. if (addr_len < sizeof(struct sockaddr_nl))
  818. return -EINVAL;
  819. if (nladdr->nl_family != AF_NETLINK)
  820. return -EINVAL;
  821. groups = nladdr->nl_groups;
  822. /* Only superuser is allowed to listen multicasts */
  823. if (groups) {
  824. if (!netlink_allowed(sock, NL_CFG_F_NONROOT_RECV))
  825. return -EPERM;
  826. err = netlink_realloc_groups(sk);
  827. if (err)
  828. return err;
  829. }
  830. if (nlk->ngroups < BITS_PER_LONG)
  831. groups &= (1UL << nlk->ngroups) - 1;
  832. /* Paired with WRITE_ONCE() in netlink_insert() */
  833. bound = READ_ONCE(nlk->bound);
  834. if (bound) {
  835. /* Ensure nlk->portid is up-to-date. */
  836. smp_rmb();
  837. if (nladdr->nl_pid != nlk->portid)
  838. return -EINVAL;
  839. }
  840. if (nlk->netlink_bind && groups) {
  841. int group;
  842. /* nl_groups is a u32, so cap the maximum groups we can bind */
  843. for (group = 0; group < BITS_PER_TYPE(u32); group++) {
  844. if (!test_bit(group, &groups))
  845. continue;
  846. err = nlk->netlink_bind(net, group + 1);
  847. if (!err)
  848. continue;
  849. netlink_undo_bind(group, groups, sk);
  850. return err;
  851. }
  852. }
  853. /* No need for barriers here as we return to user-space without
  854. * using any of the bound attributes.
  855. */
  856. netlink_lock_table();
  857. if (!bound) {
  858. err = nladdr->nl_pid ?
  859. netlink_insert(sk, nladdr->nl_pid) :
  860. netlink_autobind(sock);
  861. if (err) {
  862. netlink_undo_bind(BITS_PER_TYPE(u32), groups, sk);
  863. goto unlock;
  864. }
  865. }
  866. if (!groups && (nlk->groups == NULL || !(u32)nlk->groups[0]))
  867. goto unlock;
  868. netlink_unlock_table();
  869. netlink_table_grab();
  870. netlink_update_subscriptions(sk, nlk->subscriptions +
  871. hweight32(groups) -
  872. hweight32(nlk->groups[0]));
  873. nlk->groups[0] = (nlk->groups[0] & ~0xffffffffUL) | groups;
  874. netlink_update_listeners(sk);
  875. netlink_table_ungrab();
  876. return 0;
  877. unlock:
  878. netlink_unlock_table();
  879. return err;
  880. }
  881. static int netlink_connect(struct socket *sock, struct sockaddr *addr,
  882. int alen, int flags)
  883. {
  884. int err = 0;
  885. struct sock *sk = sock->sk;
  886. struct netlink_sock *nlk = nlk_sk(sk);
  887. struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
  888. if (alen < sizeof(addr->sa_family))
  889. return -EINVAL;
  890. if (addr->sa_family == AF_UNSPEC) {
  891. /* paired with READ_ONCE() in netlink_getsockbyportid() */
  892. WRITE_ONCE(sk->sk_state, NETLINK_UNCONNECTED);
  893. /* dst_portid and dst_group can be read locklessly */
  894. WRITE_ONCE(nlk->dst_portid, 0);
  895. WRITE_ONCE(nlk->dst_group, 0);
  896. return 0;
  897. }
  898. if (addr->sa_family != AF_NETLINK)
  899. return -EINVAL;
  900. if (alen < sizeof(struct sockaddr_nl))
  901. return -EINVAL;
  902. if ((nladdr->nl_groups || nladdr->nl_pid) &&
  903. !netlink_allowed(sock, NL_CFG_F_NONROOT_SEND))
  904. return -EPERM;
  905. /* No need for barriers here as we return to user-space without
  906. * using any of the bound attributes.
  907. * Paired with WRITE_ONCE() in netlink_insert().
  908. */
  909. if (!READ_ONCE(nlk->bound))
  910. err = netlink_autobind(sock);
  911. if (err == 0) {
  912. /* paired with READ_ONCE() in netlink_getsockbyportid() */
  913. WRITE_ONCE(sk->sk_state, NETLINK_CONNECTED);
  914. /* dst_portid and dst_group can be read locklessly */
  915. WRITE_ONCE(nlk->dst_portid, nladdr->nl_pid);
  916. WRITE_ONCE(nlk->dst_group, ffs(nladdr->nl_groups));
  917. }
  918. return err;
  919. }
  920. static int netlink_getname(struct socket *sock, struct sockaddr *addr,
  921. int peer)
  922. {
  923. struct sock *sk = sock->sk;
  924. struct netlink_sock *nlk = nlk_sk(sk);
  925. DECLARE_SOCKADDR(struct sockaddr_nl *, nladdr, addr);
  926. nladdr->nl_family = AF_NETLINK;
  927. nladdr->nl_pad = 0;
  928. if (peer) {
  929. /* Paired with WRITE_ONCE() in netlink_connect() */
  930. nladdr->nl_pid = READ_ONCE(nlk->dst_portid);
  931. nladdr->nl_groups = netlink_group_mask(READ_ONCE(nlk->dst_group));
  932. } else {
  933. /* Paired with WRITE_ONCE() in netlink_insert() */
  934. nladdr->nl_pid = READ_ONCE(nlk->portid);
  935. netlink_lock_table();
  936. nladdr->nl_groups = nlk->groups ? nlk->groups[0] : 0;
  937. netlink_unlock_table();
  938. }
  939. return sizeof(*nladdr);
  940. }
  941. static int netlink_ioctl(struct socket *sock, unsigned int cmd,
  942. unsigned long arg)
  943. {
  944. /* try to hand this ioctl down to the NIC drivers.
  945. */
  946. return -ENOIOCTLCMD;
  947. }
  948. static struct sock *netlink_getsockbyportid(struct sock *ssk, u32 portid)
  949. {
  950. struct sock *sock;
  951. struct netlink_sock *nlk;
  952. sock = netlink_lookup(sock_net(ssk), ssk->sk_protocol, portid);
  953. if (!sock)
  954. return ERR_PTR(-ECONNREFUSED);
  955. /* Don't bother queuing skb if kernel socket has no input function */
  956. nlk = nlk_sk(sock);
  957. /* dst_portid and sk_state can be changed in netlink_connect() */
  958. if (READ_ONCE(sock->sk_state) == NETLINK_CONNECTED &&
  959. READ_ONCE(nlk->dst_portid) != nlk_sk(ssk)->portid) {
  960. sock_put(sock);
  961. return ERR_PTR(-ECONNREFUSED);
  962. }
  963. return sock;
  964. }
  965. struct sock *netlink_getsockbyfilp(struct file *filp)
  966. {
  967. struct inode *inode = file_inode(filp);
  968. struct sock *sock;
  969. if (!S_ISSOCK(inode->i_mode))
  970. return ERR_PTR(-ENOTSOCK);
  971. sock = SOCKET_I(inode)->sk;
  972. if (sock->sk_family != AF_NETLINK)
  973. return ERR_PTR(-EINVAL);
  974. sock_hold(sock);
  975. return sock;
  976. }
  977. struct sk_buff *netlink_alloc_large_skb(unsigned int size, int broadcast)
  978. {
  979. size_t head_size = SKB_HEAD_ALIGN(size);
  980. struct sk_buff *skb;
  981. void *data;
  982. if (head_size <= PAGE_SIZE || broadcast)
  983. return alloc_skb(size, GFP_KERNEL);
  984. data = kvmalloc(head_size, GFP_KERNEL);
  985. if (!data)
  986. return NULL;
  987. skb = __build_skb(data, head_size);
  988. if (!skb)
  989. kvfree(data);
  990. else if (is_vmalloc_addr(data))
  991. skb->destructor = netlink_skb_destructor;
  992. return skb;
  993. }
  994. /*
  995. * Attach a skb to a netlink socket.
  996. * The caller must hold a reference to the destination socket. On error, the
  997. * reference is dropped. The skb is not send to the destination, just all
  998. * all error checks are performed and memory in the queue is reserved.
  999. * Return values:
  1000. * < 0: error. skb freed, reference to sock dropped.
  1001. * 0: continue
  1002. * 1: repeat lookup - reference dropped while waiting for socket memory.
  1003. */
  1004. int netlink_attachskb(struct sock *sk, struct sk_buff *skb,
  1005. long *timeo, struct sock *ssk)
  1006. {
  1007. DECLARE_WAITQUEUE(wait, current);
  1008. struct netlink_sock *nlk;
  1009. unsigned int rmem;
  1010. nlk = nlk_sk(sk);
  1011. rmem = atomic_add_return(skb->truesize, &sk->sk_rmem_alloc);
  1012. if ((rmem == skb->truesize || rmem <= READ_ONCE(sk->sk_rcvbuf)) &&
  1013. !test_bit(NETLINK_S_CONGESTED, &nlk->state)) {
  1014. netlink_skb_set_owner_r(skb, sk);
  1015. return 0;
  1016. }
  1017. atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
  1018. if (!*timeo) {
  1019. if (!ssk || netlink_is_kernel(ssk))
  1020. netlink_overrun(sk);
  1021. sock_put(sk);
  1022. kfree_skb(skb);
  1023. return -EAGAIN;
  1024. }
  1025. __set_current_state(TASK_INTERRUPTIBLE);
  1026. add_wait_queue(&nlk->wait, &wait);
  1027. rmem = atomic_read(&sk->sk_rmem_alloc);
  1028. if (((rmem && rmem + skb->truesize > READ_ONCE(sk->sk_rcvbuf)) ||
  1029. test_bit(NETLINK_S_CONGESTED, &nlk->state)) &&
  1030. !sock_flag(sk, SOCK_DEAD))
  1031. *timeo = schedule_timeout(*timeo);
  1032. __set_current_state(TASK_RUNNING);
  1033. remove_wait_queue(&nlk->wait, &wait);
  1034. sock_put(sk);
  1035. if (signal_pending(current)) {
  1036. kfree_skb(skb);
  1037. return sock_intr_errno(*timeo);
  1038. }
  1039. return 1;
  1040. }
  1041. static int __netlink_sendskb(struct sock *sk, struct sk_buff *skb)
  1042. {
  1043. int len = skb->len;
  1044. netlink_deliver_tap(sock_net(sk), skb);
  1045. skb_queue_tail(&sk->sk_receive_queue, skb);
  1046. sk->sk_data_ready(sk);
  1047. return len;
  1048. }
  1049. int netlink_sendskb(struct sock *sk, struct sk_buff *skb)
  1050. {
  1051. int len = __netlink_sendskb(sk, skb);
  1052. sock_put(sk);
  1053. return len;
  1054. }
  1055. void netlink_detachskb(struct sock *sk, struct sk_buff *skb)
  1056. {
  1057. kfree_skb(skb);
  1058. sock_put(sk);
  1059. }
  1060. static struct sk_buff *netlink_trim(struct sk_buff *skb, gfp_t allocation)
  1061. {
  1062. int delta;
  1063. WARN_ON(skb->sk != NULL);
  1064. delta = skb->end - skb->tail;
  1065. if (is_vmalloc_addr(skb->head) || delta * 2 < skb->truesize)
  1066. return skb;
  1067. if (skb_shared(skb)) {
  1068. struct sk_buff *nskb = skb_clone(skb, allocation);
  1069. if (!nskb)
  1070. return skb;
  1071. consume_skb(skb);
  1072. skb = nskb;
  1073. }
  1074. pskb_expand_head(skb, 0, -delta,
  1075. (allocation & ~__GFP_DIRECT_RECLAIM) |
  1076. __GFP_NOWARN | __GFP_NORETRY);
  1077. return skb;
  1078. }
  1079. static int netlink_unicast_kernel(struct sock *sk, struct sk_buff *skb,
  1080. struct sock *ssk)
  1081. {
  1082. int ret;
  1083. struct netlink_sock *nlk = nlk_sk(sk);
  1084. ret = -ECONNREFUSED;
  1085. if (nlk->netlink_rcv != NULL) {
  1086. ret = skb->len;
  1087. atomic_add(skb->truesize, &sk->sk_rmem_alloc);
  1088. netlink_skb_set_owner_r(skb, sk);
  1089. NETLINK_CB(skb).sk = ssk;
  1090. netlink_deliver_tap_kernel(sk, ssk, skb);
  1091. nlk->netlink_rcv(skb);
  1092. consume_skb(skb);
  1093. } else {
  1094. kfree_skb(skb);
  1095. }
  1096. sock_put(sk);
  1097. return ret;
  1098. }
  1099. int netlink_unicast(struct sock *ssk, struct sk_buff *skb,
  1100. u32 portid, int nonblock)
  1101. {
  1102. struct sock *sk;
  1103. int err;
  1104. long timeo;
  1105. skb = netlink_trim(skb, gfp_any());
  1106. timeo = sock_sndtimeo(ssk, nonblock);
  1107. retry:
  1108. sk = netlink_getsockbyportid(ssk, portid);
  1109. if (IS_ERR(sk)) {
  1110. kfree_skb(skb);
  1111. return PTR_ERR(sk);
  1112. }
  1113. if (netlink_is_kernel(sk))
  1114. return netlink_unicast_kernel(sk, skb, ssk);
  1115. if (sk_filter(sk, skb)) {
  1116. err = skb->len;
  1117. kfree_skb(skb);
  1118. sock_put(sk);
  1119. return err;
  1120. }
  1121. err = netlink_attachskb(sk, skb, &timeo, ssk);
  1122. if (err == 1)
  1123. goto retry;
  1124. if (err)
  1125. return err;
  1126. return netlink_sendskb(sk, skb);
  1127. }
  1128. EXPORT_SYMBOL(netlink_unicast);
  1129. int netlink_has_listeners(struct sock *sk, unsigned int group)
  1130. {
  1131. int res = 0;
  1132. struct listeners *listeners;
  1133. BUG_ON(!netlink_is_kernel(sk));
  1134. rcu_read_lock();
  1135. listeners = rcu_dereference(nl_table[sk->sk_protocol].listeners);
  1136. if (listeners && group - 1 < nl_table[sk->sk_protocol].groups)
  1137. res = test_bit(group - 1, listeners->masks);
  1138. rcu_read_unlock();
  1139. return res;
  1140. }
  1141. EXPORT_SYMBOL_GPL(netlink_has_listeners);
  1142. bool netlink_strict_get_check(struct sk_buff *skb)
  1143. {
  1144. return nlk_test_bit(STRICT_CHK, NETLINK_CB(skb).sk);
  1145. }
  1146. EXPORT_SYMBOL_GPL(netlink_strict_get_check);
  1147. static int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
  1148. {
  1149. struct netlink_sock *nlk = nlk_sk(sk);
  1150. unsigned int rmem, rcvbuf;
  1151. rmem = atomic_add_return(skb->truesize, &sk->sk_rmem_alloc);
  1152. rcvbuf = READ_ONCE(sk->sk_rcvbuf);
  1153. if ((rmem == skb->truesize || rmem <= rcvbuf) &&
  1154. !test_bit(NETLINK_S_CONGESTED, &nlk->state)) {
  1155. netlink_skb_set_owner_r(skb, sk);
  1156. __netlink_sendskb(sk, skb);
  1157. return rmem > (rcvbuf >> 1);
  1158. }
  1159. atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
  1160. return -1;
  1161. }
  1162. struct netlink_broadcast_data {
  1163. struct sock *exclude_sk;
  1164. struct net *net;
  1165. u32 portid;
  1166. u32 group;
  1167. int failure;
  1168. int delivery_failure;
  1169. int congested;
  1170. int delivered;
  1171. gfp_t allocation;
  1172. struct sk_buff *skb, *skb2;
  1173. int (*tx_filter)(struct sock *dsk, struct sk_buff *skb, void *data);
  1174. void *tx_data;
  1175. };
  1176. static void do_one_broadcast(struct sock *sk,
  1177. struct netlink_broadcast_data *p)
  1178. {
  1179. struct netlink_sock *nlk = nlk_sk(sk);
  1180. int val;
  1181. if (p->exclude_sk == sk)
  1182. return;
  1183. if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
  1184. !test_bit(p->group - 1, nlk->groups))
  1185. return;
  1186. if (!net_eq(sock_net(sk), p->net)) {
  1187. if (!nlk_test_bit(LISTEN_ALL_NSID, sk))
  1188. return;
  1189. if (!peernet_has_id(sock_net(sk), p->net))
  1190. return;
  1191. if (!file_ns_capable(sk->sk_socket->file, p->net->user_ns,
  1192. CAP_NET_BROADCAST))
  1193. return;
  1194. }
  1195. if (p->failure) {
  1196. netlink_overrun(sk);
  1197. return;
  1198. }
  1199. sock_hold(sk);
  1200. if (p->skb2 == NULL) {
  1201. if (skb_shared(p->skb)) {
  1202. p->skb2 = skb_clone(p->skb, p->allocation);
  1203. } else {
  1204. p->skb2 = skb_get(p->skb);
  1205. /*
  1206. * skb ownership may have been set when
  1207. * delivered to a previous socket.
  1208. */
  1209. skb_orphan(p->skb2);
  1210. }
  1211. }
  1212. if (p->skb2 == NULL) {
  1213. netlink_overrun(sk);
  1214. /* Clone failed. Notify ALL listeners. */
  1215. p->failure = 1;
  1216. if (nlk_test_bit(BROADCAST_SEND_ERROR, sk))
  1217. p->delivery_failure = 1;
  1218. goto out;
  1219. }
  1220. if (p->tx_filter && p->tx_filter(sk, p->skb2, p->tx_data)) {
  1221. kfree_skb(p->skb2);
  1222. p->skb2 = NULL;
  1223. goto out;
  1224. }
  1225. if (sk_filter(sk, p->skb2)) {
  1226. kfree_skb(p->skb2);
  1227. p->skb2 = NULL;
  1228. goto out;
  1229. }
  1230. NETLINK_CB(p->skb2).nsid = peernet2id(sock_net(sk), p->net);
  1231. if (NETLINK_CB(p->skb2).nsid != NETNSA_NSID_NOT_ASSIGNED)
  1232. NETLINK_CB(p->skb2).nsid_is_set = true;
  1233. val = netlink_broadcast_deliver(sk, p->skb2);
  1234. if (val < 0) {
  1235. netlink_overrun(sk);
  1236. if (nlk_test_bit(BROADCAST_SEND_ERROR, sk))
  1237. p->delivery_failure = 1;
  1238. } else {
  1239. p->congested |= val;
  1240. p->delivered = 1;
  1241. p->skb2 = NULL;
  1242. }
  1243. out:
  1244. sock_put(sk);
  1245. }
  1246. int netlink_broadcast_filtered(struct sock *ssk, struct sk_buff *skb,
  1247. u32 portid,
  1248. u32 group, gfp_t allocation,
  1249. netlink_filter_fn filter,
  1250. void *filter_data)
  1251. {
  1252. struct net *net = sock_net(ssk);
  1253. struct netlink_broadcast_data info;
  1254. struct sock *sk;
  1255. skb = netlink_trim(skb, allocation);
  1256. info.exclude_sk = ssk;
  1257. info.net = net;
  1258. info.portid = portid;
  1259. info.group = group;
  1260. info.failure = 0;
  1261. info.delivery_failure = 0;
  1262. info.congested = 0;
  1263. info.delivered = 0;
  1264. info.allocation = allocation;
  1265. info.skb = skb;
  1266. info.skb2 = NULL;
  1267. info.tx_filter = filter;
  1268. info.tx_data = filter_data;
  1269. /* While we sleep in clone, do not allow to change socket list */
  1270. netlink_lock_table();
  1271. sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
  1272. do_one_broadcast(sk, &info);
  1273. consume_skb(skb);
  1274. netlink_unlock_table();
  1275. if (info.delivery_failure) {
  1276. kfree_skb(info.skb2);
  1277. return -ENOBUFS;
  1278. }
  1279. consume_skb(info.skb2);
  1280. if (info.delivered) {
  1281. if (info.congested && gfpflags_allow_blocking(allocation))
  1282. yield();
  1283. return 0;
  1284. }
  1285. return -ESRCH;
  1286. }
  1287. EXPORT_SYMBOL(netlink_broadcast_filtered);
  1288. int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 portid,
  1289. u32 group, gfp_t allocation)
  1290. {
  1291. return netlink_broadcast_filtered(ssk, skb, portid, group, allocation,
  1292. NULL, NULL);
  1293. }
  1294. EXPORT_SYMBOL(netlink_broadcast);
  1295. struct netlink_set_err_data {
  1296. struct sock *exclude_sk;
  1297. u32 portid;
  1298. u32 group;
  1299. int code;
  1300. };
  1301. static int do_one_set_err(struct sock *sk, struct netlink_set_err_data *p)
  1302. {
  1303. struct netlink_sock *nlk = nlk_sk(sk);
  1304. int ret = 0;
  1305. if (sk == p->exclude_sk)
  1306. goto out;
  1307. if (!net_eq(sock_net(sk), sock_net(p->exclude_sk)))
  1308. goto out;
  1309. if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
  1310. !test_bit(p->group - 1, nlk->groups))
  1311. goto out;
  1312. if (p->code == ENOBUFS && nlk_test_bit(RECV_NO_ENOBUFS, sk)) {
  1313. ret = 1;
  1314. goto out;
  1315. }
  1316. WRITE_ONCE(sk->sk_err, p->code);
  1317. sk_error_report(sk);
  1318. out:
  1319. return ret;
  1320. }
  1321. /**
  1322. * netlink_set_err - report error to broadcast listeners
  1323. * @ssk: the kernel netlink socket, as returned by netlink_kernel_create()
  1324. * @portid: the PORTID of a process that we want to skip (if any)
  1325. * @group: the broadcast group that will notice the error
  1326. * @code: error code, must be negative (as usual in kernelspace)
  1327. *
  1328. * This function returns the number of broadcast listeners that have set the
  1329. * NETLINK_NO_ENOBUFS socket option.
  1330. */
  1331. int netlink_set_err(struct sock *ssk, u32 portid, u32 group, int code)
  1332. {
  1333. struct netlink_set_err_data info;
  1334. unsigned long flags;
  1335. struct sock *sk;
  1336. int ret = 0;
  1337. info.exclude_sk = ssk;
  1338. info.portid = portid;
  1339. info.group = group;
  1340. /* sk->sk_err wants a positive error value */
  1341. info.code = -code;
  1342. read_lock_irqsave(&nl_table_lock, flags);
  1343. sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
  1344. ret += do_one_set_err(sk, &info);
  1345. read_unlock_irqrestore(&nl_table_lock, flags);
  1346. return ret;
  1347. }
  1348. EXPORT_SYMBOL(netlink_set_err);
  1349. /* must be called with netlink table grabbed */
  1350. static void netlink_update_socket_mc(struct netlink_sock *nlk,
  1351. unsigned int group,
  1352. int is_new)
  1353. {
  1354. int old, new = !!is_new, subscriptions;
  1355. old = test_bit(group - 1, nlk->groups);
  1356. subscriptions = nlk->subscriptions - old + new;
  1357. __assign_bit(group - 1, nlk->groups, new);
  1358. netlink_update_subscriptions(&nlk->sk, subscriptions);
  1359. netlink_update_listeners(&nlk->sk);
  1360. }
  1361. static int netlink_setsockopt(struct socket *sock, int level, int optname,
  1362. sockptr_t optval, unsigned int optlen)
  1363. {
  1364. struct sock *sk = sock->sk;
  1365. struct netlink_sock *nlk = nlk_sk(sk);
  1366. unsigned int val = 0;
  1367. int nr = -1;
  1368. if (level != SOL_NETLINK)
  1369. return -ENOPROTOOPT;
  1370. if (optlen >= sizeof(int) &&
  1371. copy_from_sockptr(&val, optval, sizeof(val)))
  1372. return -EFAULT;
  1373. switch (optname) {
  1374. case NETLINK_PKTINFO:
  1375. nr = NETLINK_F_RECV_PKTINFO;
  1376. break;
  1377. case NETLINK_ADD_MEMBERSHIP:
  1378. case NETLINK_DROP_MEMBERSHIP: {
  1379. int err;
  1380. if (!netlink_allowed(sock, NL_CFG_F_NONROOT_RECV))
  1381. return -EPERM;
  1382. err = netlink_realloc_groups(sk);
  1383. if (err)
  1384. return err;
  1385. if (!val || val - 1 >= nlk->ngroups)
  1386. return -EINVAL;
  1387. if (optname == NETLINK_ADD_MEMBERSHIP && nlk->netlink_bind) {
  1388. err = nlk->netlink_bind(sock_net(sk), val);
  1389. if (err)
  1390. return err;
  1391. }
  1392. netlink_table_grab();
  1393. netlink_update_socket_mc(nlk, val,
  1394. optname == NETLINK_ADD_MEMBERSHIP);
  1395. netlink_table_ungrab();
  1396. if (optname == NETLINK_DROP_MEMBERSHIP && nlk->netlink_unbind)
  1397. nlk->netlink_unbind(sock_net(sk), val);
  1398. break;
  1399. }
  1400. case NETLINK_BROADCAST_ERROR:
  1401. nr = NETLINK_F_BROADCAST_SEND_ERROR;
  1402. break;
  1403. case NETLINK_NO_ENOBUFS:
  1404. assign_bit(NETLINK_F_RECV_NO_ENOBUFS, &nlk->flags, val);
  1405. if (val) {
  1406. clear_bit(NETLINK_S_CONGESTED, &nlk->state);
  1407. wake_up_interruptible(&nlk->wait);
  1408. }
  1409. break;
  1410. case NETLINK_LISTEN_ALL_NSID:
  1411. if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_BROADCAST))
  1412. return -EPERM;
  1413. nr = NETLINK_F_LISTEN_ALL_NSID;
  1414. break;
  1415. case NETLINK_CAP_ACK:
  1416. nr = NETLINK_F_CAP_ACK;
  1417. break;
  1418. case NETLINK_EXT_ACK:
  1419. nr = NETLINK_F_EXT_ACK;
  1420. break;
  1421. case NETLINK_GET_STRICT_CHK:
  1422. nr = NETLINK_F_STRICT_CHK;
  1423. break;
  1424. default:
  1425. return -ENOPROTOOPT;
  1426. }
  1427. if (nr >= 0)
  1428. assign_bit(nr, &nlk->flags, val);
  1429. return 0;
  1430. }
  1431. static int netlink_getsockopt(struct socket *sock, int level, int optname,
  1432. char __user *optval, int __user *optlen)
  1433. {
  1434. struct sock *sk = sock->sk;
  1435. struct netlink_sock *nlk = nlk_sk(sk);
  1436. unsigned int flag;
  1437. int len, val;
  1438. if (level != SOL_NETLINK)
  1439. return -ENOPROTOOPT;
  1440. if (get_user(len, optlen))
  1441. return -EFAULT;
  1442. if (len < 0)
  1443. return -EINVAL;
  1444. switch (optname) {
  1445. case NETLINK_PKTINFO:
  1446. flag = NETLINK_F_RECV_PKTINFO;
  1447. break;
  1448. case NETLINK_BROADCAST_ERROR:
  1449. flag = NETLINK_F_BROADCAST_SEND_ERROR;
  1450. break;
  1451. case NETLINK_NO_ENOBUFS:
  1452. flag = NETLINK_F_RECV_NO_ENOBUFS;
  1453. break;
  1454. case NETLINK_LIST_MEMBERSHIPS: {
  1455. int pos, idx, shift, err = 0;
  1456. netlink_lock_table();
  1457. for (pos = 0; pos * 8 < nlk->ngroups; pos += sizeof(u32)) {
  1458. if (len - pos < sizeof(u32))
  1459. break;
  1460. idx = pos / sizeof(unsigned long);
  1461. shift = (pos % sizeof(unsigned long)) * 8;
  1462. if (put_user((u32)(nlk->groups[idx] >> shift),
  1463. (u32 __user *)(optval + pos))) {
  1464. err = -EFAULT;
  1465. break;
  1466. }
  1467. }
  1468. if (put_user(ALIGN(BITS_TO_BYTES(nlk->ngroups), sizeof(u32)), optlen))
  1469. err = -EFAULT;
  1470. netlink_unlock_table();
  1471. return err;
  1472. }
  1473. case NETLINK_LISTEN_ALL_NSID:
  1474. flag = NETLINK_F_LISTEN_ALL_NSID;
  1475. break;
  1476. case NETLINK_CAP_ACK:
  1477. flag = NETLINK_F_CAP_ACK;
  1478. break;
  1479. case NETLINK_EXT_ACK:
  1480. flag = NETLINK_F_EXT_ACK;
  1481. break;
  1482. case NETLINK_GET_STRICT_CHK:
  1483. flag = NETLINK_F_STRICT_CHK;
  1484. break;
  1485. default:
  1486. return -ENOPROTOOPT;
  1487. }
  1488. if (len < sizeof(int))
  1489. return -EINVAL;
  1490. len = sizeof(int);
  1491. val = test_bit(flag, &nlk->flags);
  1492. if (put_user(len, optlen) ||
  1493. copy_to_user(optval, &val, len))
  1494. return -EFAULT;
  1495. return 0;
  1496. }
  1497. static void netlink_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb)
  1498. {
  1499. struct nl_pktinfo info;
  1500. info.group = NETLINK_CB(skb).dst_group;
  1501. put_cmsg(msg, SOL_NETLINK, NETLINK_PKTINFO, sizeof(info), &info);
  1502. }
  1503. static void netlink_cmsg_listen_all_nsid(struct sock *sk, struct msghdr *msg,
  1504. struct sk_buff *skb)
  1505. {
  1506. if (!NETLINK_CB(skb).nsid_is_set)
  1507. return;
  1508. put_cmsg(msg, SOL_NETLINK, NETLINK_LISTEN_ALL_NSID, sizeof(int),
  1509. &NETLINK_CB(skb).nsid);
  1510. }
  1511. static int netlink_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
  1512. {
  1513. struct sock *sk = sock->sk;
  1514. struct netlink_sock *nlk = nlk_sk(sk);
  1515. DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
  1516. u32 dst_portid;
  1517. u32 dst_group;
  1518. struct sk_buff *skb;
  1519. int err;
  1520. struct scm_cookie scm;
  1521. u32 netlink_skb_flags = 0;
  1522. if (msg->msg_flags & MSG_OOB)
  1523. return -EOPNOTSUPP;
  1524. if (len == 0) {
  1525. pr_warn_once("Zero length message leads to an empty skb\n");
  1526. return -ENODATA;
  1527. }
  1528. err = scm_send(sock, msg, &scm, true);
  1529. if (err < 0)
  1530. return err;
  1531. if (msg->msg_namelen) {
  1532. err = -EINVAL;
  1533. if (msg->msg_namelen < sizeof(struct sockaddr_nl))
  1534. goto out;
  1535. if (addr->nl_family != AF_NETLINK)
  1536. goto out;
  1537. dst_portid = addr->nl_pid;
  1538. dst_group = ffs(addr->nl_groups);
  1539. err = -EPERM;
  1540. if ((dst_group || dst_portid) &&
  1541. !netlink_allowed(sock, NL_CFG_F_NONROOT_SEND))
  1542. goto out;
  1543. netlink_skb_flags |= NETLINK_SKB_DST;
  1544. } else {
  1545. /* Paired with WRITE_ONCE() in netlink_connect() */
  1546. dst_portid = READ_ONCE(nlk->dst_portid);
  1547. dst_group = READ_ONCE(nlk->dst_group);
  1548. }
  1549. /* Paired with WRITE_ONCE() in netlink_insert() */
  1550. if (!READ_ONCE(nlk->bound)) {
  1551. err = netlink_autobind(sock);
  1552. if (err)
  1553. goto out;
  1554. } else {
  1555. /* Ensure nlk is hashed and visible. */
  1556. smp_rmb();
  1557. }
  1558. err = -EMSGSIZE;
  1559. if (len > sk->sk_sndbuf - 32)
  1560. goto out;
  1561. err = -ENOBUFS;
  1562. skb = netlink_alloc_large_skb(len, dst_group);
  1563. if (skb == NULL)
  1564. goto out;
  1565. NETLINK_CB(skb).portid = nlk->portid;
  1566. NETLINK_CB(skb).dst_group = dst_group;
  1567. NETLINK_CB(skb).creds = scm.creds;
  1568. NETLINK_CB(skb).flags = netlink_skb_flags;
  1569. err = -EFAULT;
  1570. if (memcpy_from_msg(skb_put(skb, len), msg, len)) {
  1571. kfree_skb(skb);
  1572. goto out;
  1573. }
  1574. err = security_netlink_send(sk, skb);
  1575. if (err) {
  1576. kfree_skb(skb);
  1577. goto out;
  1578. }
  1579. if (dst_group) {
  1580. refcount_inc(&skb->users);
  1581. netlink_broadcast(sk, skb, dst_portid, dst_group, GFP_KERNEL);
  1582. }
  1583. err = netlink_unicast(sk, skb, dst_portid, msg->msg_flags & MSG_DONTWAIT);
  1584. out:
  1585. scm_destroy(&scm);
  1586. return err;
  1587. }
  1588. static int netlink_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
  1589. int flags)
  1590. {
  1591. struct scm_cookie scm;
  1592. struct sock *sk = sock->sk;
  1593. struct netlink_sock *nlk = nlk_sk(sk);
  1594. size_t copied, max_recvmsg_len;
  1595. struct sk_buff *skb, *data_skb;
  1596. int err, ret;
  1597. if (flags & MSG_OOB)
  1598. return -EOPNOTSUPP;
  1599. copied = 0;
  1600. skb = skb_recv_datagram(sk, flags, &err);
  1601. if (skb == NULL)
  1602. goto out;
  1603. data_skb = skb;
  1604. #ifdef CONFIG_COMPAT_NETLINK_MESSAGES
  1605. if (unlikely(skb_shinfo(skb)->frag_list)) {
  1606. /*
  1607. * If this skb has a frag_list, then here that means that we
  1608. * will have to use the frag_list skb's data for compat tasks
  1609. * and the regular skb's data for normal (non-compat) tasks.
  1610. *
  1611. * If we need to send the compat skb, assign it to the
  1612. * 'data_skb' variable so that it will be used below for data
  1613. * copying. We keep 'skb' for everything else, including
  1614. * freeing both later.
  1615. */
  1616. if (flags & MSG_CMSG_COMPAT)
  1617. data_skb = skb_shinfo(skb)->frag_list;
  1618. }
  1619. #endif
  1620. /* Record the max length of recvmsg() calls for future allocations */
  1621. max_recvmsg_len = max(READ_ONCE(nlk->max_recvmsg_len), len);
  1622. max_recvmsg_len = min_t(size_t, max_recvmsg_len,
  1623. SKB_WITH_OVERHEAD(32768));
  1624. WRITE_ONCE(nlk->max_recvmsg_len, max_recvmsg_len);
  1625. copied = data_skb->len;
  1626. if (len < copied) {
  1627. msg->msg_flags |= MSG_TRUNC;
  1628. copied = len;
  1629. }
  1630. err = skb_copy_datagram_msg(data_skb, 0, msg, copied);
  1631. if (msg->msg_name) {
  1632. DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
  1633. addr->nl_family = AF_NETLINK;
  1634. addr->nl_pad = 0;
  1635. addr->nl_pid = NETLINK_CB(skb).portid;
  1636. addr->nl_groups = netlink_group_mask(NETLINK_CB(skb).dst_group);
  1637. msg->msg_namelen = sizeof(*addr);
  1638. }
  1639. if (nlk_test_bit(RECV_PKTINFO, sk))
  1640. netlink_cmsg_recv_pktinfo(msg, skb);
  1641. if (nlk_test_bit(LISTEN_ALL_NSID, sk))
  1642. netlink_cmsg_listen_all_nsid(sk, msg, skb);
  1643. memset(&scm, 0, sizeof(scm));
  1644. scm.creds = *NETLINK_CREDS(skb);
  1645. if (flags & MSG_TRUNC)
  1646. copied = data_skb->len;
  1647. skb_free_datagram(sk, skb);
  1648. if (READ_ONCE(nlk->cb_running) &&
  1649. atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) {
  1650. ret = netlink_dump(sk, false);
  1651. if (ret) {
  1652. WRITE_ONCE(sk->sk_err, -ret);
  1653. sk_error_report(sk);
  1654. }
  1655. }
  1656. scm_recv(sock, msg, &scm, flags);
  1657. out:
  1658. netlink_rcv_wake(sk);
  1659. return err ? : copied;
  1660. }
  1661. static void netlink_data_ready(struct sock *sk)
  1662. {
  1663. BUG();
  1664. }
  1665. /*
  1666. * We export these functions to other modules. They provide a
  1667. * complete set of kernel non-blocking support for message
  1668. * queueing.
  1669. */
  1670. struct sock *
  1671. __netlink_kernel_create(struct net *net, int unit, struct module *module,
  1672. struct netlink_kernel_cfg *cfg)
  1673. {
  1674. struct socket *sock;
  1675. struct sock *sk;
  1676. struct netlink_sock *nlk;
  1677. struct listeners *listeners = NULL;
  1678. unsigned int groups;
  1679. BUG_ON(!nl_table);
  1680. if (unit < 0 || unit >= MAX_LINKS)
  1681. return NULL;
  1682. if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
  1683. return NULL;
  1684. if (__netlink_create(net, sock, unit, 1) < 0)
  1685. goto out_sock_release_nosk;
  1686. sk = sock->sk;
  1687. if (!cfg || cfg->groups < 32)
  1688. groups = 32;
  1689. else
  1690. groups = cfg->groups;
  1691. listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
  1692. if (!listeners)
  1693. goto out_sock_release;
  1694. sk->sk_data_ready = netlink_data_ready;
  1695. if (cfg && cfg->input)
  1696. nlk_sk(sk)->netlink_rcv = cfg->input;
  1697. if (netlink_insert(sk, 0))
  1698. goto out_sock_release;
  1699. nlk = nlk_sk(sk);
  1700. set_bit(NETLINK_F_KERNEL_SOCKET, &nlk->flags);
  1701. netlink_table_grab();
  1702. if (!nl_table[unit].registered) {
  1703. nl_table[unit].groups = groups;
  1704. rcu_assign_pointer(nl_table[unit].listeners, listeners);
  1705. nl_table[unit].module = module;
  1706. if (cfg) {
  1707. nl_table[unit].bind = cfg->bind;
  1708. nl_table[unit].unbind = cfg->unbind;
  1709. nl_table[unit].release = cfg->release;
  1710. nl_table[unit].flags = cfg->flags;
  1711. }
  1712. nl_table[unit].registered = 1;
  1713. } else {
  1714. kfree(listeners);
  1715. nl_table[unit].registered++;
  1716. }
  1717. netlink_table_ungrab();
  1718. return sk;
  1719. out_sock_release:
  1720. kfree(listeners);
  1721. netlink_kernel_release(sk);
  1722. return NULL;
  1723. out_sock_release_nosk:
  1724. sock_release(sock);
  1725. return NULL;
  1726. }
  1727. EXPORT_SYMBOL(__netlink_kernel_create);
  1728. void
  1729. netlink_kernel_release(struct sock *sk)
  1730. {
  1731. if (sk == NULL || sk->sk_socket == NULL)
  1732. return;
  1733. sock_release(sk->sk_socket);
  1734. }
  1735. EXPORT_SYMBOL(netlink_kernel_release);
  1736. int __netlink_change_ngroups(struct sock *sk, unsigned int groups)
  1737. {
  1738. struct listeners *new, *old;
  1739. struct netlink_table *tbl = &nl_table[sk->sk_protocol];
  1740. if (groups < 32)
  1741. groups = 32;
  1742. if (NLGRPSZ(tbl->groups) < NLGRPSZ(groups)) {
  1743. new = kzalloc(sizeof(*new) + NLGRPSZ(groups), GFP_ATOMIC);
  1744. if (!new)
  1745. return -ENOMEM;
  1746. old = nl_deref_protected(tbl->listeners);
  1747. memcpy(new->masks, old->masks, NLGRPSZ(tbl->groups));
  1748. rcu_assign_pointer(tbl->listeners, new);
  1749. kfree_rcu(old, rcu);
  1750. }
  1751. tbl->groups = groups;
  1752. return 0;
  1753. }
  1754. /**
  1755. * netlink_change_ngroups - change number of multicast groups
  1756. *
  1757. * This changes the number of multicast groups that are available
  1758. * on a certain netlink family. Note that it is not possible to
  1759. * change the number of groups to below 32. Also note that it does
  1760. * not implicitly call netlink_clear_multicast_users() when the
  1761. * number of groups is reduced.
  1762. *
  1763. * @sk: The kernel netlink socket, as returned by netlink_kernel_create().
  1764. * @groups: The new number of groups.
  1765. */
  1766. int netlink_change_ngroups(struct sock *sk, unsigned int groups)
  1767. {
  1768. int err;
  1769. netlink_table_grab();
  1770. err = __netlink_change_ngroups(sk, groups);
  1771. netlink_table_ungrab();
  1772. return err;
  1773. }
  1774. void __netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
  1775. {
  1776. struct sock *sk;
  1777. struct netlink_table *tbl = &nl_table[ksk->sk_protocol];
  1778. struct hlist_node *tmp;
  1779. sk_for_each_bound_safe(sk, tmp, &tbl->mc_list)
  1780. netlink_update_socket_mc(nlk_sk(sk), group, 0);
  1781. }
  1782. struct nlmsghdr *
  1783. __nlmsg_put(struct sk_buff *skb, u32 portid, u32 seq, int type, int len, int flags)
  1784. {
  1785. struct nlmsghdr *nlh;
  1786. int size = nlmsg_msg_size(len);
  1787. nlh = skb_put(skb, NLMSG_ALIGN(size));
  1788. nlh->nlmsg_type = type;
  1789. nlh->nlmsg_len = size;
  1790. nlh->nlmsg_flags = flags;
  1791. nlh->nlmsg_pid = portid;
  1792. nlh->nlmsg_seq = seq;
  1793. if (!__builtin_constant_p(size) || NLMSG_ALIGN(size) - size != 0)
  1794. memset(nlmsg_data(nlh) + len, 0, NLMSG_ALIGN(size) - size);
  1795. return nlh;
  1796. }
  1797. EXPORT_SYMBOL(__nlmsg_put);
  1798. static size_t
  1799. netlink_ack_tlv_len(struct netlink_sock *nlk, int err,
  1800. const struct netlink_ext_ack *extack)
  1801. {
  1802. size_t tlvlen;
  1803. if (!extack || !test_bit(NETLINK_F_EXT_ACK, &nlk->flags))
  1804. return 0;
  1805. tlvlen = 0;
  1806. if (extack->_msg)
  1807. tlvlen += nla_total_size(strlen(extack->_msg) + 1);
  1808. if (extack->cookie_len)
  1809. tlvlen += nla_total_size(extack->cookie_len);
  1810. /* Following attributes are only reported as error (not warning) */
  1811. if (!err)
  1812. return tlvlen;
  1813. if (extack->bad_attr)
  1814. tlvlen += nla_total_size(sizeof(u32));
  1815. if (extack->policy)
  1816. tlvlen += netlink_policy_dump_attr_size_estimate(extack->policy);
  1817. if (extack->miss_type)
  1818. tlvlen += nla_total_size(sizeof(u32));
  1819. if (extack->miss_nest)
  1820. tlvlen += nla_total_size(sizeof(u32));
  1821. return tlvlen;
  1822. }
  1823. static bool nlmsg_check_in_payload(const struct nlmsghdr *nlh, const void *addr)
  1824. {
  1825. return !WARN_ON(addr < nlmsg_data(nlh) ||
  1826. addr - (const void *) nlh >= nlh->nlmsg_len);
  1827. }
  1828. static void
  1829. netlink_ack_tlv_fill(struct sk_buff *skb, const struct nlmsghdr *nlh, int err,
  1830. const struct netlink_ext_ack *extack)
  1831. {
  1832. if (extack->_msg)
  1833. WARN_ON(nla_put_string(skb, NLMSGERR_ATTR_MSG, extack->_msg));
  1834. if (extack->cookie_len)
  1835. WARN_ON(nla_put(skb, NLMSGERR_ATTR_COOKIE,
  1836. extack->cookie_len, extack->cookie));
  1837. if (!err)
  1838. return;
  1839. if (extack->bad_attr && nlmsg_check_in_payload(nlh, extack->bad_attr))
  1840. WARN_ON(nla_put_u32(skb, NLMSGERR_ATTR_OFFS,
  1841. (u8 *)extack->bad_attr - (const u8 *)nlh));
  1842. if (extack->policy)
  1843. netlink_policy_dump_write_attr(skb, extack->policy,
  1844. NLMSGERR_ATTR_POLICY);
  1845. if (extack->miss_type)
  1846. WARN_ON(nla_put_u32(skb, NLMSGERR_ATTR_MISS_TYPE,
  1847. extack->miss_type));
  1848. if (extack->miss_nest && nlmsg_check_in_payload(nlh, extack->miss_nest))
  1849. WARN_ON(nla_put_u32(skb, NLMSGERR_ATTR_MISS_NEST,
  1850. (u8 *)extack->miss_nest - (const u8 *)nlh));
  1851. }
  1852. /*
  1853. * It looks a bit ugly.
  1854. * It would be better to create kernel thread.
  1855. */
  1856. static int netlink_dump_done(struct netlink_sock *nlk, struct sk_buff *skb,
  1857. struct netlink_callback *cb,
  1858. struct netlink_ext_ack *extack)
  1859. {
  1860. struct nlmsghdr *nlh;
  1861. size_t extack_len;
  1862. nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE, sizeof(nlk->dump_done_errno),
  1863. NLM_F_MULTI | cb->answer_flags);
  1864. if (WARN_ON(!nlh))
  1865. return -ENOBUFS;
  1866. nl_dump_check_consistent(cb, nlh);
  1867. memcpy(nlmsg_data(nlh), &nlk->dump_done_errno, sizeof(nlk->dump_done_errno));
  1868. extack_len = netlink_ack_tlv_len(nlk, nlk->dump_done_errno, extack);
  1869. if (extack_len) {
  1870. nlh->nlmsg_flags |= NLM_F_ACK_TLVS;
  1871. if (skb_tailroom(skb) >= extack_len) {
  1872. netlink_ack_tlv_fill(skb, cb->nlh,
  1873. nlk->dump_done_errno, extack);
  1874. nlmsg_end(skb, nlh);
  1875. }
  1876. }
  1877. return 0;
  1878. }
  1879. static int netlink_dump(struct sock *sk, bool lock_taken)
  1880. {
  1881. struct netlink_sock *nlk = nlk_sk(sk);
  1882. struct netlink_ext_ack extack = {};
  1883. struct netlink_callback *cb;
  1884. struct sk_buff *skb = NULL;
  1885. unsigned int rmem, rcvbuf;
  1886. size_t max_recvmsg_len;
  1887. struct module *module;
  1888. int err = -ENOBUFS;
  1889. int alloc_min_size;
  1890. int alloc_size;
  1891. if (!lock_taken)
  1892. mutex_lock(&nlk->nl_cb_mutex);
  1893. if (!nlk->cb_running) {
  1894. err = -EINVAL;
  1895. goto errout_skb;
  1896. }
  1897. /* NLMSG_GOODSIZE is small to avoid high order allocations being
  1898. * required, but it makes sense to _attempt_ a 16K bytes allocation
  1899. * to reduce number of system calls on dump operations, if user
  1900. * ever provided a big enough buffer.
  1901. */
  1902. cb = &nlk->cb;
  1903. alloc_min_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE);
  1904. max_recvmsg_len = READ_ONCE(nlk->max_recvmsg_len);
  1905. if (alloc_min_size < max_recvmsg_len) {
  1906. alloc_size = max_recvmsg_len;
  1907. skb = alloc_skb(alloc_size,
  1908. (GFP_KERNEL & ~__GFP_DIRECT_RECLAIM) |
  1909. __GFP_NOWARN | __GFP_NORETRY);
  1910. }
  1911. if (!skb) {
  1912. alloc_size = alloc_min_size;
  1913. skb = alloc_skb(alloc_size, GFP_KERNEL);
  1914. }
  1915. if (!skb)
  1916. goto errout_skb;
  1917. rcvbuf = READ_ONCE(sk->sk_rcvbuf);
  1918. rmem = atomic_add_return(skb->truesize, &sk->sk_rmem_alloc);
  1919. if (rmem != skb->truesize && rmem >= rcvbuf) {
  1920. atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
  1921. goto errout_skb;
  1922. }
  1923. /* Trim skb to allocated size. User is expected to provide buffer as
  1924. * large as max(min_dump_alloc, 16KiB (mac_recvmsg_len capped at
  1925. * netlink_recvmsg())). dump will pack as many smaller messages as
  1926. * could fit within the allocated skb. skb is typically allocated
  1927. * with larger space than required (could be as much as near 2x the
  1928. * requested size with align to next power of 2 approach). Allowing
  1929. * dump to use the excess space makes it difficult for a user to have a
  1930. * reasonable static buffer based on the expected largest dump of a
  1931. * single netdev. The outcome is MSG_TRUNC error.
  1932. */
  1933. skb_reserve(skb, skb_tailroom(skb) - alloc_size);
  1934. /* Make sure malicious BPF programs can not read unitialized memory
  1935. * from skb->head -> skb->data
  1936. */
  1937. skb_reset_network_header(skb);
  1938. skb_reset_mac_header(skb);
  1939. netlink_skb_set_owner_r(skb, sk);
  1940. if (nlk->dump_done_errno > 0) {
  1941. cb->extack = &extack;
  1942. nlk->dump_done_errno = cb->dump(skb, cb);
  1943. /* EMSGSIZE plus something already in the skb means
  1944. * that there's more to dump but current skb has filled up.
  1945. * If the callback really wants to return EMSGSIZE to user space
  1946. * it needs to do so again, on the next cb->dump() call,
  1947. * without putting data in the skb.
  1948. */
  1949. if (nlk->dump_done_errno == -EMSGSIZE && skb->len)
  1950. nlk->dump_done_errno = skb->len;
  1951. cb->extack = NULL;
  1952. }
  1953. if (nlk->dump_done_errno > 0 ||
  1954. skb_tailroom(skb) < nlmsg_total_size(sizeof(nlk->dump_done_errno))) {
  1955. mutex_unlock(&nlk->nl_cb_mutex);
  1956. if (sk_filter(sk, skb))
  1957. kfree_skb(skb);
  1958. else
  1959. __netlink_sendskb(sk, skb);
  1960. return 0;
  1961. }
  1962. if (netlink_dump_done(nlk, skb, cb, &extack))
  1963. goto errout_skb;
  1964. #ifdef CONFIG_COMPAT_NETLINK_MESSAGES
  1965. /* frag_list skb's data is used for compat tasks
  1966. * and the regular skb's data for normal (non-compat) tasks.
  1967. * See netlink_recvmsg().
  1968. */
  1969. if (unlikely(skb_shinfo(skb)->frag_list)) {
  1970. if (netlink_dump_done(nlk, skb_shinfo(skb)->frag_list, cb, &extack))
  1971. goto errout_skb;
  1972. }
  1973. #endif
  1974. if (sk_filter(sk, skb))
  1975. kfree_skb(skb);
  1976. else
  1977. __netlink_sendskb(sk, skb);
  1978. if (cb->done)
  1979. cb->done(cb);
  1980. WRITE_ONCE(nlk->cb_running, false);
  1981. module = cb->module;
  1982. skb = cb->skb;
  1983. mutex_unlock(&nlk->nl_cb_mutex);
  1984. module_put(module);
  1985. consume_skb(skb);
  1986. return 0;
  1987. errout_skb:
  1988. mutex_unlock(&nlk->nl_cb_mutex);
  1989. kfree_skb(skb);
  1990. return err;
  1991. }
  1992. int __netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
  1993. const struct nlmsghdr *nlh,
  1994. struct netlink_dump_control *control)
  1995. {
  1996. struct netlink_callback *cb;
  1997. struct netlink_sock *nlk;
  1998. struct sock *sk;
  1999. int ret;
  2000. refcount_inc(&skb->users);
  2001. sk = netlink_lookup(sock_net(ssk), ssk->sk_protocol, NETLINK_CB(skb).portid);
  2002. if (sk == NULL) {
  2003. ret = -ECONNREFUSED;
  2004. goto error_free;
  2005. }
  2006. nlk = nlk_sk(sk);
  2007. mutex_lock(&nlk->nl_cb_mutex);
  2008. /* A dump is in progress... */
  2009. if (nlk->cb_running) {
  2010. ret = -EBUSY;
  2011. goto error_unlock;
  2012. }
  2013. /* add reference of module which cb->dump belongs to */
  2014. if (!try_module_get(control->module)) {
  2015. ret = -EPROTONOSUPPORT;
  2016. goto error_unlock;
  2017. }
  2018. cb = &nlk->cb;
  2019. memset(cb, 0, sizeof(*cb));
  2020. cb->dump = control->dump;
  2021. cb->done = control->done;
  2022. cb->nlh = nlh;
  2023. cb->data = control->data;
  2024. cb->module = control->module;
  2025. cb->min_dump_alloc = control->min_dump_alloc;
  2026. cb->flags = control->flags;
  2027. cb->skb = skb;
  2028. cb->strict_check = nlk_test_bit(STRICT_CHK, NETLINK_CB(skb).sk);
  2029. if (control->start) {
  2030. cb->extack = control->extack;
  2031. ret = control->start(cb);
  2032. cb->extack = NULL;
  2033. if (ret)
  2034. goto error_put;
  2035. }
  2036. WRITE_ONCE(nlk->cb_running, true);
  2037. nlk->dump_done_errno = INT_MAX;
  2038. ret = netlink_dump(sk, true);
  2039. sock_put(sk);
  2040. if (ret)
  2041. return ret;
  2042. /* We successfully started a dump, by returning -EINTR we
  2043. * signal not to send ACK even if it was requested.
  2044. */
  2045. return -EINTR;
  2046. error_put:
  2047. module_put(control->module);
  2048. error_unlock:
  2049. sock_put(sk);
  2050. mutex_unlock(&nlk->nl_cb_mutex);
  2051. error_free:
  2052. kfree_skb(skb);
  2053. return ret;
  2054. }
  2055. EXPORT_SYMBOL(__netlink_dump_start);
  2056. void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err,
  2057. const struct netlink_ext_ack *extack)
  2058. {
  2059. struct sk_buff *skb;
  2060. struct nlmsghdr *rep;
  2061. struct nlmsgerr *errmsg;
  2062. size_t payload = sizeof(*errmsg);
  2063. struct netlink_sock *nlk = nlk_sk(NETLINK_CB(in_skb).sk);
  2064. unsigned int flags = 0;
  2065. size_t tlvlen;
  2066. /* Error messages get the original request appened, unless the user
  2067. * requests to cap the error message, and get extra error data if
  2068. * requested.
  2069. */
  2070. if (err && !test_bit(NETLINK_F_CAP_ACK, &nlk->flags))
  2071. payload += nlmsg_len(nlh);
  2072. else
  2073. flags |= NLM_F_CAPPED;
  2074. tlvlen = netlink_ack_tlv_len(nlk, err, extack);
  2075. if (tlvlen)
  2076. flags |= NLM_F_ACK_TLVS;
  2077. skb = nlmsg_new(payload + tlvlen, GFP_KERNEL);
  2078. if (!skb)
  2079. goto err_skb;
  2080. rep = nlmsg_put(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq,
  2081. NLMSG_ERROR, sizeof(*errmsg), flags);
  2082. if (!rep)
  2083. goto err_bad_put;
  2084. errmsg = nlmsg_data(rep);
  2085. errmsg->error = err;
  2086. errmsg->msg = *nlh;
  2087. if (!(flags & NLM_F_CAPPED)) {
  2088. if (!nlmsg_append(skb, nlmsg_len(nlh)))
  2089. goto err_bad_put;
  2090. memcpy(nlmsg_data(&errmsg->msg), nlmsg_data(nlh),
  2091. nlmsg_len(nlh));
  2092. }
  2093. if (tlvlen)
  2094. netlink_ack_tlv_fill(skb, nlh, err, extack);
  2095. nlmsg_end(skb, rep);
  2096. nlmsg_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).portid);
  2097. return;
  2098. err_bad_put:
  2099. nlmsg_free(skb);
  2100. err_skb:
  2101. WRITE_ONCE(NETLINK_CB(in_skb).sk->sk_err, ENOBUFS);
  2102. sk_error_report(NETLINK_CB(in_skb).sk);
  2103. }
  2104. EXPORT_SYMBOL(netlink_ack);
  2105. int netlink_rcv_skb(struct sk_buff *skb, int (*cb)(struct sk_buff *,
  2106. struct nlmsghdr *,
  2107. struct netlink_ext_ack *))
  2108. {
  2109. struct netlink_ext_ack extack;
  2110. struct nlmsghdr *nlh;
  2111. int err;
  2112. while (skb->len >= nlmsg_total_size(0)) {
  2113. int msglen;
  2114. memset(&extack, 0, sizeof(extack));
  2115. nlh = nlmsg_hdr(skb);
  2116. err = 0;
  2117. if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len)
  2118. return 0;
  2119. /* Only requests are handled by the kernel */
  2120. if (!(nlh->nlmsg_flags & NLM_F_REQUEST))
  2121. goto ack;
  2122. /* Skip control messages */
  2123. if (nlh->nlmsg_type < NLMSG_MIN_TYPE)
  2124. goto ack;
  2125. err = cb(skb, nlh, &extack);
  2126. if (err == -EINTR)
  2127. goto skip;
  2128. ack:
  2129. if (nlh->nlmsg_flags & NLM_F_ACK || err)
  2130. netlink_ack(skb, nlh, err, &extack);
  2131. skip:
  2132. msglen = NLMSG_ALIGN(nlh->nlmsg_len);
  2133. if (msglen > skb->len)
  2134. msglen = skb->len;
  2135. skb_pull(skb, msglen);
  2136. }
  2137. return 0;
  2138. }
  2139. EXPORT_SYMBOL(netlink_rcv_skb);
  2140. /**
  2141. * nlmsg_notify - send a notification netlink message
  2142. * @sk: netlink socket to use
  2143. * @skb: notification message
  2144. * @portid: destination netlink portid for reports or 0
  2145. * @group: destination multicast group or 0
  2146. * @report: 1 to report back, 0 to disable
  2147. * @flags: allocation flags
  2148. */
  2149. int nlmsg_notify(struct sock *sk, struct sk_buff *skb, u32 portid,
  2150. unsigned int group, int report, gfp_t flags)
  2151. {
  2152. int err = 0;
  2153. if (group) {
  2154. int exclude_portid = 0;
  2155. if (report) {
  2156. refcount_inc(&skb->users);
  2157. exclude_portid = portid;
  2158. }
  2159. /* errors reported via destination sk->sk_err, but propagate
  2160. * delivery errors if NETLINK_BROADCAST_ERROR flag is set */
  2161. err = nlmsg_multicast(sk, skb, exclude_portid, group, flags);
  2162. if (err == -ESRCH)
  2163. err = 0;
  2164. }
  2165. if (report) {
  2166. int err2;
  2167. err2 = nlmsg_unicast(sk, skb, portid);
  2168. if (!err)
  2169. err = err2;
  2170. }
  2171. return err;
  2172. }
  2173. EXPORT_SYMBOL(nlmsg_notify);
  2174. #ifdef CONFIG_PROC_FS
  2175. struct nl_seq_iter {
  2176. struct seq_net_private p;
  2177. struct rhashtable_iter hti;
  2178. int link;
  2179. };
  2180. static void netlink_walk_start(struct nl_seq_iter *iter)
  2181. {
  2182. rhashtable_walk_enter(&nl_table[iter->link].hash, &iter->hti);
  2183. rhashtable_walk_start(&iter->hti);
  2184. }
  2185. static void netlink_walk_stop(struct nl_seq_iter *iter)
  2186. {
  2187. rhashtable_walk_stop(&iter->hti);
  2188. rhashtable_walk_exit(&iter->hti);
  2189. }
  2190. static void *__netlink_seq_next(struct seq_file *seq)
  2191. {
  2192. struct nl_seq_iter *iter = seq->private;
  2193. struct netlink_sock *nlk;
  2194. do {
  2195. for (;;) {
  2196. nlk = rhashtable_walk_next(&iter->hti);
  2197. if (IS_ERR(nlk)) {
  2198. if (PTR_ERR(nlk) == -EAGAIN)
  2199. continue;
  2200. return nlk;
  2201. }
  2202. if (nlk)
  2203. break;
  2204. netlink_walk_stop(iter);
  2205. if (++iter->link >= MAX_LINKS)
  2206. return NULL;
  2207. netlink_walk_start(iter);
  2208. }
  2209. } while (sock_net(&nlk->sk) != seq_file_net(seq));
  2210. return nlk;
  2211. }
  2212. static void *netlink_seq_start(struct seq_file *seq, loff_t *posp)
  2213. __acquires(RCU)
  2214. {
  2215. struct nl_seq_iter *iter = seq->private;
  2216. void *obj = SEQ_START_TOKEN;
  2217. loff_t pos;
  2218. iter->link = 0;
  2219. netlink_walk_start(iter);
  2220. for (pos = *posp; pos && obj && !IS_ERR(obj); pos--)
  2221. obj = __netlink_seq_next(seq);
  2222. return obj;
  2223. }
  2224. static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
  2225. {
  2226. ++*pos;
  2227. return __netlink_seq_next(seq);
  2228. }
  2229. static void netlink_native_seq_stop(struct seq_file *seq, void *v)
  2230. {
  2231. struct nl_seq_iter *iter = seq->private;
  2232. if (iter->link >= MAX_LINKS)
  2233. return;
  2234. netlink_walk_stop(iter);
  2235. }
  2236. static int netlink_native_seq_show(struct seq_file *seq, void *v)
  2237. {
  2238. if (v == SEQ_START_TOKEN) {
  2239. seq_puts(seq,
  2240. "sk Eth Pid Groups "
  2241. "Rmem Wmem Dump Locks Drops Inode\n");
  2242. } else {
  2243. struct sock *s = v;
  2244. struct netlink_sock *nlk = nlk_sk(s);
  2245. seq_printf(seq, "%pK %-3d %-10u %08x %-8d %-8d %-5d %-8d %-8u %-8lu\n",
  2246. s,
  2247. s->sk_protocol,
  2248. nlk->portid,
  2249. nlk->groups ? (u32)nlk->groups[0] : 0,
  2250. sk_rmem_alloc_get(s),
  2251. sk_wmem_alloc_get(s),
  2252. READ_ONCE(nlk->cb_running),
  2253. refcount_read(&s->sk_refcnt),
  2254. atomic_read(&s->sk_drops),
  2255. sock_i_ino(s)
  2256. );
  2257. }
  2258. return 0;
  2259. }
  2260. #ifdef CONFIG_BPF_SYSCALL
  2261. struct bpf_iter__netlink {
  2262. __bpf_md_ptr(struct bpf_iter_meta *, meta);
  2263. __bpf_md_ptr(struct netlink_sock *, sk);
  2264. };
  2265. DEFINE_BPF_ITER_FUNC(netlink, struct bpf_iter_meta *meta, struct netlink_sock *sk)
  2266. static int netlink_prog_seq_show(struct bpf_prog *prog,
  2267. struct bpf_iter_meta *meta,
  2268. void *v)
  2269. {
  2270. struct bpf_iter__netlink ctx;
  2271. meta->seq_num--; /* skip SEQ_START_TOKEN */
  2272. ctx.meta = meta;
  2273. ctx.sk = nlk_sk((struct sock *)v);
  2274. return bpf_iter_run_prog(prog, &ctx);
  2275. }
  2276. static int netlink_seq_show(struct seq_file *seq, void *v)
  2277. {
  2278. struct bpf_iter_meta meta;
  2279. struct bpf_prog *prog;
  2280. meta.seq = seq;
  2281. prog = bpf_iter_get_info(&meta, false);
  2282. if (!prog)
  2283. return netlink_native_seq_show(seq, v);
  2284. if (v != SEQ_START_TOKEN)
  2285. return netlink_prog_seq_show(prog, &meta, v);
  2286. return 0;
  2287. }
  2288. static void netlink_seq_stop(struct seq_file *seq, void *v)
  2289. {
  2290. struct bpf_iter_meta meta;
  2291. struct bpf_prog *prog;
  2292. if (!v) {
  2293. meta.seq = seq;
  2294. prog = bpf_iter_get_info(&meta, true);
  2295. if (prog)
  2296. (void)netlink_prog_seq_show(prog, &meta, v);
  2297. }
  2298. netlink_native_seq_stop(seq, v);
  2299. }
  2300. #else
  2301. static int netlink_seq_show(struct seq_file *seq, void *v)
  2302. {
  2303. return netlink_native_seq_show(seq, v);
  2304. }
  2305. static void netlink_seq_stop(struct seq_file *seq, void *v)
  2306. {
  2307. netlink_native_seq_stop(seq, v);
  2308. }
  2309. #endif
  2310. static const struct seq_operations netlink_seq_ops = {
  2311. .start = netlink_seq_start,
  2312. .next = netlink_seq_next,
  2313. .stop = netlink_seq_stop,
  2314. .show = netlink_seq_show,
  2315. };
  2316. #endif
  2317. int netlink_register_notifier(struct notifier_block *nb)
  2318. {
  2319. return blocking_notifier_chain_register(&netlink_chain, nb);
  2320. }
  2321. EXPORT_SYMBOL(netlink_register_notifier);
  2322. int netlink_unregister_notifier(struct notifier_block *nb)
  2323. {
  2324. return blocking_notifier_chain_unregister(&netlink_chain, nb);
  2325. }
  2326. EXPORT_SYMBOL(netlink_unregister_notifier);
  2327. static const struct proto_ops netlink_ops = {
  2328. .family = PF_NETLINK,
  2329. .owner = THIS_MODULE,
  2330. .release = netlink_release,
  2331. .bind = netlink_bind,
  2332. .connect = netlink_connect,
  2333. .socketpair = sock_no_socketpair,
  2334. .accept = sock_no_accept,
  2335. .getname = netlink_getname,
  2336. .poll = datagram_poll,
  2337. .ioctl = netlink_ioctl,
  2338. .listen = sock_no_listen,
  2339. .shutdown = sock_no_shutdown,
  2340. .setsockopt = netlink_setsockopt,
  2341. .getsockopt = netlink_getsockopt,
  2342. .sendmsg = netlink_sendmsg,
  2343. .recvmsg = netlink_recvmsg,
  2344. .mmap = sock_no_mmap,
  2345. };
  2346. static const struct net_proto_family netlink_family_ops = {
  2347. .family = PF_NETLINK,
  2348. .create = netlink_create,
  2349. .owner = THIS_MODULE, /* for consistency 8) */
  2350. };
  2351. static int __net_init netlink_net_init(struct net *net)
  2352. {
  2353. #ifdef CONFIG_PROC_FS
  2354. if (!proc_create_net("netlink", 0, net->proc_net, &netlink_seq_ops,
  2355. sizeof(struct nl_seq_iter)))
  2356. return -ENOMEM;
  2357. #endif
  2358. return 0;
  2359. }
  2360. static void __net_exit netlink_net_exit(struct net *net)
  2361. {
  2362. #ifdef CONFIG_PROC_FS
  2363. remove_proc_entry("netlink", net->proc_net);
  2364. #endif
  2365. }
  2366. static void __init netlink_add_usersock_entry(void)
  2367. {
  2368. struct listeners *listeners;
  2369. int groups = 32;
  2370. listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
  2371. if (!listeners)
  2372. panic("netlink_add_usersock_entry: Cannot allocate listeners\n");
  2373. netlink_table_grab();
  2374. nl_table[NETLINK_USERSOCK].groups = groups;
  2375. rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners);
  2376. nl_table[NETLINK_USERSOCK].module = THIS_MODULE;
  2377. nl_table[NETLINK_USERSOCK].registered = 1;
  2378. nl_table[NETLINK_USERSOCK].flags = NL_CFG_F_NONROOT_SEND;
  2379. netlink_table_ungrab();
  2380. }
  2381. static struct pernet_operations __net_initdata netlink_net_ops = {
  2382. .init = netlink_net_init,
  2383. .exit = netlink_net_exit,
  2384. };
  2385. static inline u32 netlink_hash(const void *data, u32 len, u32 seed)
  2386. {
  2387. const struct netlink_sock *nlk = data;
  2388. struct netlink_compare_arg arg;
  2389. netlink_compare_arg_init(&arg, sock_net(&nlk->sk), nlk->portid);
  2390. return jhash2((u32 *)&arg, netlink_compare_arg_len / sizeof(u32), seed);
  2391. }
  2392. static const struct rhashtable_params netlink_rhashtable_params = {
  2393. .head_offset = offsetof(struct netlink_sock, node),
  2394. .key_len = netlink_compare_arg_len,
  2395. .obj_hashfn = netlink_hash,
  2396. .obj_cmpfn = netlink_compare,
  2397. .automatic_shrinking = true,
  2398. };
  2399. #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
  2400. BTF_ID_LIST(btf_netlink_sock_id)
  2401. BTF_ID(struct, netlink_sock)
  2402. static const struct bpf_iter_seq_info netlink_seq_info = {
  2403. .seq_ops = &netlink_seq_ops,
  2404. .init_seq_private = bpf_iter_init_seq_net,
  2405. .fini_seq_private = bpf_iter_fini_seq_net,
  2406. .seq_priv_size = sizeof(struct nl_seq_iter),
  2407. };
  2408. static struct bpf_iter_reg netlink_reg_info = {
  2409. .target = "netlink",
  2410. .ctx_arg_info_size = 1,
  2411. .ctx_arg_info = {
  2412. { offsetof(struct bpf_iter__netlink, sk),
  2413. PTR_TO_BTF_ID_OR_NULL },
  2414. },
  2415. .seq_info = &netlink_seq_info,
  2416. };
  2417. static int __init bpf_iter_register(void)
  2418. {
  2419. netlink_reg_info.ctx_arg_info[0].btf_id = *btf_netlink_sock_id;
  2420. return bpf_iter_reg_target(&netlink_reg_info);
  2421. }
  2422. #endif
  2423. static int __init netlink_proto_init(void)
  2424. {
  2425. int i;
  2426. int err = proto_register(&netlink_proto, 0);
  2427. if (err != 0)
  2428. goto out;
  2429. #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
  2430. err = bpf_iter_register();
  2431. if (err)
  2432. goto out;
  2433. #endif
  2434. BUILD_BUG_ON(sizeof(struct netlink_skb_parms) > sizeof_field(struct sk_buff, cb));
  2435. nl_table = kcalloc(MAX_LINKS, sizeof(*nl_table), GFP_KERNEL);
  2436. if (!nl_table)
  2437. goto panic;
  2438. for (i = 0; i < MAX_LINKS; i++) {
  2439. if (rhashtable_init(&nl_table[i].hash,
  2440. &netlink_rhashtable_params) < 0) {
  2441. while (--i > 0)
  2442. rhashtable_destroy(&nl_table[i].hash);
  2443. kfree(nl_table);
  2444. goto panic;
  2445. }
  2446. }
  2447. netlink_add_usersock_entry();
  2448. sock_register(&netlink_family_ops);
  2449. register_pernet_subsys(&netlink_net_ops);
  2450. register_pernet_subsys(&netlink_tap_net_ops);
  2451. /* The netlink device handler may be needed early. */
  2452. rtnetlink_init();
  2453. out:
  2454. return err;
  2455. panic:
  2456. panic("netlink_init: Cannot allocate nl_table\n");
  2457. }
  2458. core_initcall(netlink_proto_init);