af_netlink.c 70 KB

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