]> git.itanic.dy.fi Git - linux-stable/blob - fs/smb/client/sess.c
a16e175731eb3b5b76d0472bcefd695bac30c968
[linux-stable] / fs / smb / client / sess.c
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3  *
4  *   SMB/CIFS session setup handling routines
5  *
6  *   Copyright (c) International Business Machines  Corp., 2006, 2009
7  *   Author(s): Steve French (sfrench@us.ibm.com)
8  *
9  */
10
11 #include "cifspdu.h"
12 #include "cifsglob.h"
13 #include "cifsproto.h"
14 #include "cifs_unicode.h"
15 #include "cifs_debug.h"
16 #include "ntlmssp.h"
17 #include "nterr.h"
18 #include <linux/utsname.h>
19 #include <linux/slab.h>
20 #include <linux/version.h>
21 #include "cifsfs.h"
22 #include "cifs_spnego.h"
23 #include "smb2proto.h"
24 #include "fs_context.h"
25
26 static int
27 cifs_ses_add_channel(struct cifs_ses *ses,
28                      struct cifs_server_iface *iface);
29
30 bool
31 is_server_using_iface(struct TCP_Server_Info *server,
32                       struct cifs_server_iface *iface)
33 {
34         struct sockaddr_in *i4 = (struct sockaddr_in *)&iface->sockaddr;
35         struct sockaddr_in6 *i6 = (struct sockaddr_in6 *)&iface->sockaddr;
36         struct sockaddr_in *s4 = (struct sockaddr_in *)&server->dstaddr;
37         struct sockaddr_in6 *s6 = (struct sockaddr_in6 *)&server->dstaddr;
38
39         if (server->dstaddr.ss_family != iface->sockaddr.ss_family)
40                 return false;
41         if (server->dstaddr.ss_family == AF_INET) {
42                 if (s4->sin_addr.s_addr != i4->sin_addr.s_addr)
43                         return false;
44         } else if (server->dstaddr.ss_family == AF_INET6) {
45                 if (memcmp(&s6->sin6_addr, &i6->sin6_addr,
46                            sizeof(i6->sin6_addr)) != 0)
47                         return false;
48         } else {
49                 /* unknown family.. */
50                 return false;
51         }
52         return true;
53 }
54
55 bool is_ses_using_iface(struct cifs_ses *ses, struct cifs_server_iface *iface)
56 {
57         int i;
58
59         spin_lock(&ses->chan_lock);
60         for (i = 0; i < ses->chan_count; i++) {
61                 if (ses->chans[i].iface == iface) {
62                         spin_unlock(&ses->chan_lock);
63                         return true;
64                 }
65         }
66         spin_unlock(&ses->chan_lock);
67         return false;
68 }
69
70 /* channel helper functions. assumed that chan_lock is held by caller. */
71
72 int
73 cifs_ses_get_chan_index(struct cifs_ses *ses,
74                         struct TCP_Server_Info *server)
75 {
76         unsigned int i;
77
78         for (i = 0; i < ses->chan_count; i++) {
79                 if (ses->chans[i].server == server)
80                         return i;
81         }
82
83         /* If we didn't find the channel, it is likely a bug */
84         if (server)
85                 cifs_dbg(VFS, "unable to get chan index for server: 0x%llx",
86                          server->conn_id);
87         WARN_ON(1);
88         return CIFS_INVAL_CHAN_INDEX;
89 }
90
91 void
92 cifs_chan_set_in_reconnect(struct cifs_ses *ses,
93                              struct TCP_Server_Info *server)
94 {
95         int chan_index = cifs_ses_get_chan_index(ses, server);
96
97         if (chan_index == CIFS_INVAL_CHAN_INDEX)
98                 return;
99
100         ses->chans[chan_index].in_reconnect = true;
101 }
102
103 void
104 cifs_chan_clear_in_reconnect(struct cifs_ses *ses,
105                              struct TCP_Server_Info *server)
106 {
107         unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
108
109         if (chan_index == CIFS_INVAL_CHAN_INDEX)
110                 return;
111
112         ses->chans[chan_index].in_reconnect = false;
113 }
114
115 bool
116 cifs_chan_in_reconnect(struct cifs_ses *ses,
117                           struct TCP_Server_Info *server)
118 {
119         unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
120
121         if (chan_index == CIFS_INVAL_CHAN_INDEX)
122                 return true;    /* err on the safer side */
123
124         return CIFS_CHAN_IN_RECONNECT(ses, chan_index);
125 }
126
127 void
128 cifs_chan_set_need_reconnect(struct cifs_ses *ses,
129                              struct TCP_Server_Info *server)
130 {
131         unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
132
133         if (chan_index == CIFS_INVAL_CHAN_INDEX)
134                 return;
135
136         set_bit(chan_index, &ses->chans_need_reconnect);
137         cifs_dbg(FYI, "Set reconnect bitmask for chan %u; now 0x%lx\n",
138                  chan_index, ses->chans_need_reconnect);
139 }
140
141 void
142 cifs_chan_clear_need_reconnect(struct cifs_ses *ses,
143                                struct TCP_Server_Info *server)
144 {
145         unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
146
147         if (chan_index == CIFS_INVAL_CHAN_INDEX)
148                 return;
149
150         clear_bit(chan_index, &ses->chans_need_reconnect);
151         cifs_dbg(FYI, "Cleared reconnect bitmask for chan %u; now 0x%lx\n",
152                  chan_index, ses->chans_need_reconnect);
153 }
154
155 bool
156 cifs_chan_needs_reconnect(struct cifs_ses *ses,
157                           struct TCP_Server_Info *server)
158 {
159         unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
160
161         if (chan_index == CIFS_INVAL_CHAN_INDEX)
162                 return true;    /* err on the safer side */
163
164         return CIFS_CHAN_NEEDS_RECONNECT(ses, chan_index);
165 }
166
167 bool
168 cifs_chan_is_iface_active(struct cifs_ses *ses,
169                           struct TCP_Server_Info *server)
170 {
171         unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
172
173         if (chan_index == CIFS_INVAL_CHAN_INDEX)
174                 return true;    /* err on the safer side */
175
176         return ses->chans[chan_index].iface &&
177                 ses->chans[chan_index].iface->is_active;
178 }
179
180 /* returns number of channels added */
181 int cifs_try_adding_channels(struct cifs_ses *ses)
182 {
183         struct TCP_Server_Info *server = ses->server;
184         int old_chan_count, new_chan_count;
185         int left;
186         int rc = 0;
187         int tries = 0;
188         size_t iface_weight = 0, iface_min_speed = 0;
189         struct cifs_server_iface *iface = NULL, *niface = NULL;
190         struct cifs_server_iface *last_iface = NULL;
191
192         spin_lock(&ses->chan_lock);
193
194         new_chan_count = old_chan_count = ses->chan_count;
195         left = ses->chan_max - ses->chan_count;
196
197         if (left <= 0) {
198                 spin_unlock(&ses->chan_lock);
199                 cifs_dbg(FYI,
200                          "ses already at max_channels (%zu), nothing to open\n",
201                          ses->chan_max);
202                 return 0;
203         }
204
205         if (server->dialect < SMB30_PROT_ID) {
206                 spin_unlock(&ses->chan_lock);
207                 cifs_dbg(VFS, "multichannel is not supported on this protocol version, use 3.0 or above\n");
208                 return 0;
209         }
210
211         if (!(server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
212                 spin_unlock(&ses->chan_lock);
213                 cifs_server_dbg(VFS, "no multichannel support\n");
214                 return 0;
215         }
216         spin_unlock(&ses->chan_lock);
217
218         while (left > 0) {
219
220                 tries++;
221                 if (tries > 3*ses->chan_max) {
222                         cifs_dbg(VFS, "too many channel open attempts (%d channels left to open)\n",
223                                  left);
224                         break;
225                 }
226
227                 spin_lock(&ses->iface_lock);
228                 if (!ses->iface_count) {
229                         spin_unlock(&ses->iface_lock);
230                         cifs_dbg(VFS, "server %s does not advertise interfaces\n",
231                                       ses->server->hostname);
232                         break;
233                 }
234
235                 if (!iface)
236                         iface = list_first_entry(&ses->iface_list, struct cifs_server_iface,
237                                                  iface_head);
238                 last_iface = list_last_entry(&ses->iface_list, struct cifs_server_iface,
239                                              iface_head);
240                 iface_min_speed = last_iface->speed;
241
242                 list_for_each_entry_safe_from(iface, niface, &ses->iface_list,
243                                     iface_head) {
244                         /* do not mix rdma and non-rdma interfaces */
245                         if (iface->rdma_capable != ses->server->rdma)
246                                 continue;
247
248                         /* skip ifaces that are unusable */
249                         if (!iface->is_active ||
250                             (is_ses_using_iface(ses, iface) &&
251                              !iface->rss_capable))
252                                 continue;
253
254                         /* check if we already allocated enough channels */
255                         iface_weight = iface->speed / iface_min_speed;
256
257                         if (iface->weight_fulfilled >= iface_weight)
258                                 continue;
259
260                         /* take ref before unlock */
261                         kref_get(&iface->refcount);
262
263                         spin_unlock(&ses->iface_lock);
264                         rc = cifs_ses_add_channel(ses, iface);
265                         spin_lock(&ses->iface_lock);
266
267                         if (rc) {
268                                 cifs_dbg(VFS, "failed to open extra channel on iface:%pIS rc=%d\n",
269                                          &iface->sockaddr,
270                                          rc);
271                                 kref_put(&iface->refcount, release_iface);
272                                 continue;
273                         }
274
275                         iface->num_channels++;
276                         iface->weight_fulfilled++;
277                         cifs_dbg(VFS, "successfully opened new channel on iface:%pIS\n",
278                                  &iface->sockaddr);
279                         break;
280                 }
281
282                 /* reached end of list. reset weight_fulfilled and start over */
283                 if (list_entry_is_head(iface, &ses->iface_list, iface_head)) {
284                         list_for_each_entry(iface, &ses->iface_list, iface_head)
285                                 iface->weight_fulfilled = 0;
286                         spin_unlock(&ses->iface_lock);
287                         iface = NULL;
288                         continue;
289                 }
290                 spin_unlock(&ses->iface_lock);
291
292                 left--;
293                 new_chan_count++;
294         }
295
296         return new_chan_count - old_chan_count;
297 }
298
299 /*
300  * called when multichannel is disabled by the server.
301  * this always gets called from smb2_reconnect
302  * and cannot get called in parallel threads.
303  */
304 void
305 cifs_disable_secondary_channels(struct cifs_ses *ses)
306 {
307         int i, chan_count;
308         struct TCP_Server_Info *server;
309         struct cifs_server_iface *iface;
310
311         spin_lock(&ses->chan_lock);
312         chan_count = ses->chan_count;
313         if (chan_count == 1)
314                 goto done;
315
316         ses->chan_count = 1;
317
318         /* for all secondary channels reset the need reconnect bit */
319         ses->chans_need_reconnect &= 1;
320
321         for (i = 1; i < chan_count; i++) {
322                 iface = ses->chans[i].iface;
323                 server = ses->chans[i].server;
324
325                 /*
326                  * remove these references first, since we need to unlock
327                  * the chan_lock here, since iface_lock is a higher lock
328                  */
329                 ses->chans[i].iface = NULL;
330                 ses->chans[i].server = NULL;
331                 spin_unlock(&ses->chan_lock);
332
333                 if (iface) {
334                         spin_lock(&ses->iface_lock);
335                         iface->num_channels--;
336                         if (iface->weight_fulfilled)
337                                 iface->weight_fulfilled--;
338                         kref_put(&iface->refcount, release_iface);
339                         spin_unlock(&ses->iface_lock);
340                 }
341
342                 if (server) {
343                         if (!server->terminate) {
344                                 server->terminate = true;
345                                 cifs_signal_cifsd_for_reconnect(server, false);
346                         }
347                         cifs_put_tcp_session(server, false);
348                 }
349
350                 spin_lock(&ses->chan_lock);
351         }
352
353 done:
354         spin_unlock(&ses->chan_lock);
355 }
356
357 /*
358  * update the iface for the channel if necessary.
359  * will return 0 when iface is updated, 1 if removed, 2 otherwise
360  * Must be called with chan_lock held.
361  */
362 int
363 cifs_chan_update_iface(struct cifs_ses *ses, struct TCP_Server_Info *server)
364 {
365         unsigned int chan_index;
366         size_t iface_weight = 0, iface_min_speed = 0;
367         struct cifs_server_iface *iface = NULL;
368         struct cifs_server_iface *old_iface = NULL;
369         struct cifs_server_iface *last_iface = NULL;
370         struct sockaddr_storage ss;
371         int rc = 0;
372
373         spin_lock(&ses->chan_lock);
374         chan_index = cifs_ses_get_chan_index(ses, server);
375         if (chan_index == CIFS_INVAL_CHAN_INDEX) {
376                 spin_unlock(&ses->chan_lock);
377                 return 0;
378         }
379
380         if (ses->chans[chan_index].iface) {
381                 old_iface = ses->chans[chan_index].iface;
382                 if (old_iface->is_active) {
383                         spin_unlock(&ses->chan_lock);
384                         return 1;
385                 }
386         }
387         spin_unlock(&ses->chan_lock);
388
389         spin_lock(&server->srv_lock);
390         ss = server->dstaddr;
391         spin_unlock(&server->srv_lock);
392
393         spin_lock(&ses->iface_lock);
394         if (!ses->iface_count) {
395                 spin_unlock(&ses->iface_lock);
396                 cifs_dbg(VFS, "server %s does not advertise interfaces\n", ses->server->hostname);
397                 return 0;
398         }
399
400         last_iface = list_last_entry(&ses->iface_list, struct cifs_server_iface,
401                                      iface_head);
402         iface_min_speed = last_iface->speed;
403
404         /* then look for a new one */
405         list_for_each_entry(iface, &ses->iface_list, iface_head) {
406                 if (!chan_index) {
407                         /* if we're trying to get the updated iface for primary channel */
408                         if (!cifs_match_ipaddr((struct sockaddr *) &ss,
409                                                (struct sockaddr *) &iface->sockaddr))
410                                 continue;
411
412                         kref_get(&iface->refcount);
413                         break;
414                 }
415
416                 /* do not mix rdma and non-rdma interfaces */
417                 if (iface->rdma_capable != server->rdma)
418                         continue;
419
420                 if (!iface->is_active ||
421                     (is_ses_using_iface(ses, iface) &&
422                      !iface->rss_capable)) {
423                         continue;
424                 }
425
426                 /* check if we already allocated enough channels */
427                 iface_weight = iface->speed / iface_min_speed;
428
429                 if (iface->weight_fulfilled >= iface_weight)
430                         continue;
431
432                 kref_get(&iface->refcount);
433                 break;
434         }
435
436         if (list_entry_is_head(iface, &ses->iface_list, iface_head)) {
437                 rc = 1;
438                 iface = NULL;
439                 cifs_dbg(FYI, "unable to find a suitable iface\n");
440         }
441
442         if (!iface) {
443                 if (!chan_index)
444                         cifs_dbg(FYI, "unable to get the interface matching: %pIS\n",
445                                  &ss);
446                 else {
447                         cifs_dbg(FYI, "unable to find another interface to replace: %pIS\n",
448                                  &old_iface->sockaddr);
449                 }
450
451                 spin_unlock(&ses->iface_lock);
452                 return 0;
453         }
454
455         /* now drop the ref to the current iface */
456         if (old_iface) {
457                 cifs_dbg(FYI, "replacing iface: %pIS with %pIS\n",
458                          &old_iface->sockaddr,
459                          &iface->sockaddr);
460
461                 old_iface->num_channels--;
462                 if (old_iface->weight_fulfilled)
463                         old_iface->weight_fulfilled--;
464                 iface->num_channels++;
465                 iface->weight_fulfilled++;
466
467                 kref_put(&old_iface->refcount, release_iface);
468         } else if (!chan_index) {
469                 /* special case: update interface for primary channel */
470                 if (iface) {
471                         cifs_dbg(FYI, "referencing primary channel iface: %pIS\n",
472                                  &iface->sockaddr);
473                         iface->num_channels++;
474                         iface->weight_fulfilled++;
475                 }
476         }
477         spin_unlock(&ses->iface_lock);
478
479         if (iface) {
480                 spin_lock(&ses->chan_lock);
481                 chan_index = cifs_ses_get_chan_index(ses, server);
482                 if (chan_index == CIFS_INVAL_CHAN_INDEX) {
483                         spin_unlock(&ses->chan_lock);
484                         return 0;
485                 }
486
487                 ses->chans[chan_index].iface = iface;
488                 spin_unlock(&ses->chan_lock);
489         }
490
491         return rc;
492 }
493
494 /*
495  * If server is a channel of ses, return the corresponding enclosing
496  * cifs_chan otherwise return NULL.
497  */
498 struct cifs_chan *
499 cifs_ses_find_chan(struct cifs_ses *ses, struct TCP_Server_Info *server)
500 {
501         int i;
502
503         spin_lock(&ses->chan_lock);
504         for (i = 0; i < ses->chan_count; i++) {
505                 if (ses->chans[i].server == server) {
506                         spin_unlock(&ses->chan_lock);
507                         return &ses->chans[i];
508                 }
509         }
510         spin_unlock(&ses->chan_lock);
511         return NULL;
512 }
513
514 static int
515 cifs_ses_add_channel(struct cifs_ses *ses,
516                      struct cifs_server_iface *iface)
517 {
518         struct TCP_Server_Info *chan_server;
519         struct cifs_chan *chan;
520         struct smb3_fs_context *ctx;
521         static const char unc_fmt[] = "\\%s\\foo";
522         struct sockaddr_in *ipv4 = (struct sockaddr_in *)&iface->sockaddr;
523         struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&iface->sockaddr;
524         size_t len;
525         int rc;
526         unsigned int xid = get_xid();
527
528         if (iface->sockaddr.ss_family == AF_INET)
529                 cifs_dbg(FYI, "adding channel to ses %p (speed:%zu bps rdma:%s ip:%pI4)\n",
530                          ses, iface->speed, iface->rdma_capable ? "yes" : "no",
531                          &ipv4->sin_addr);
532         else
533                 cifs_dbg(FYI, "adding channel to ses %p (speed:%zu bps rdma:%s ip:%pI6)\n",
534                          ses, iface->speed, iface->rdma_capable ? "yes" : "no",
535                          &ipv6->sin6_addr);
536
537         /*
538          * Setup a ctx with mostly the same info as the existing
539          * session and overwrite it with the requested iface data.
540          *
541          * We need to setup at least the fields used for negprot and
542          * sesssetup.
543          *
544          * We only need the ctx here, so we can reuse memory from
545          * the session and server without caring about memory
546          * management.
547          */
548         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
549         if (!ctx) {
550                 rc = -ENOMEM;
551                 goto out_free_xid;
552         }
553
554         /* Always make new connection for now (TODO?) */
555         ctx->nosharesock = true;
556
557         /* Auth */
558         ctx->domainauto = ses->domainAuto;
559         ctx->domainname = ses->domainName;
560
561         /* no hostname for extra channels */
562         ctx->server_hostname = "";
563
564         ctx->username = ses->user_name;
565         ctx->password = ses->password;
566         ctx->sectype = ses->sectype;
567         ctx->sign = ses->sign;
568
569         /* UNC and paths */
570         /* XXX: Use ses->server->hostname? */
571         len = sizeof(unc_fmt) + SERVER_NAME_LEN_WITH_NULL;
572         ctx->UNC = kzalloc(len, GFP_KERNEL);
573         if (!ctx->UNC) {
574                 rc = -ENOMEM;
575                 goto out_free_ctx;
576         }
577         scnprintf(ctx->UNC, len, unc_fmt, ses->ip_addr);
578         ctx->prepath = "";
579
580         /* Reuse same version as master connection */
581         ctx->vals = ses->server->vals;
582         ctx->ops = ses->server->ops;
583
584         ctx->noblocksnd = ses->server->noblocksnd;
585         ctx->noautotune = ses->server->noautotune;
586         ctx->sockopt_tcp_nodelay = ses->server->tcp_nodelay;
587         ctx->echo_interval = ses->server->echo_interval / HZ;
588         ctx->max_credits = ses->server->max_credits;
589
590         /*
591          * This will be used for encoding/decoding user/domain/pw
592          * during sess setup auth.
593          */
594         ctx->local_nls = ses->local_nls;
595
596         /* Use RDMA if possible */
597         ctx->rdma = iface->rdma_capable;
598         memcpy(&ctx->dstaddr, &iface->sockaddr, sizeof(ctx->dstaddr));
599
600         /* reuse master con client guid */
601         memcpy(&ctx->client_guid, ses->server->client_guid,
602                sizeof(ctx->client_guid));
603         ctx->use_client_guid = true;
604
605         chan_server = cifs_get_tcp_session(ctx, ses->server);
606
607         spin_lock(&ses->chan_lock);
608         chan = &ses->chans[ses->chan_count];
609         chan->server = chan_server;
610         if (IS_ERR(chan->server)) {
611                 rc = PTR_ERR(chan->server);
612                 chan->server = NULL;
613                 spin_unlock(&ses->chan_lock);
614                 goto out;
615         }
616         chan->iface = iface;
617         ses->chan_count++;
618         atomic_set(&ses->chan_seq, 0);
619
620         /* Mark this channel as needing connect/setup */
621         cifs_chan_set_need_reconnect(ses, chan->server);
622
623         spin_unlock(&ses->chan_lock);
624
625         mutex_lock(&ses->session_mutex);
626         /*
627          * We need to allocate the server crypto now as we will need
628          * to sign packets before we generate the channel signing key
629          * (we sign with the session key)
630          */
631         rc = smb311_crypto_shash_allocate(chan->server);
632         if (rc) {
633                 cifs_dbg(VFS, "%s: crypto alloc failed\n", __func__);
634                 mutex_unlock(&ses->session_mutex);
635                 goto out;
636         }
637
638         rc = cifs_negotiate_protocol(xid, ses, chan->server);
639         if (!rc)
640                 rc = cifs_setup_session(xid, ses, chan->server, ses->local_nls);
641
642         mutex_unlock(&ses->session_mutex);
643
644 out:
645         if (rc && chan->server) {
646                 cifs_put_tcp_session(chan->server, 0);
647
648                 spin_lock(&ses->chan_lock);
649
650                 /* we rely on all bits beyond chan_count to be clear */
651                 cifs_chan_clear_need_reconnect(ses, chan->server);
652                 ses->chan_count--;
653                 /*
654                  * chan_count should never reach 0 as at least the primary
655                  * channel is always allocated
656                  */
657                 WARN_ON(ses->chan_count < 1);
658                 spin_unlock(&ses->chan_lock);
659         }
660
661         kfree(ctx->UNC);
662 out_free_ctx:
663         kfree(ctx);
664 out_free_xid:
665         free_xid(xid);
666         return rc;
667 }
668
669 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
670 static __u32 cifs_ssetup_hdr(struct cifs_ses *ses,
671                              struct TCP_Server_Info *server,
672                              SESSION_SETUP_ANDX *pSMB)
673 {
674         __u32 capabilities = 0;
675
676         /* init fields common to all four types of SessSetup */
677         /* Note that offsets for first seven fields in req struct are same  */
678         /*      in CIFS Specs so does not matter which of 3 forms of struct */
679         /*      that we use in next few lines                               */
680         /* Note that header is initialized to zero in header_assemble */
681         pSMB->req.AndXCommand = 0xFF;
682         pSMB->req.MaxBufferSize = cpu_to_le16(min_t(u32,
683                                         CIFSMaxBufSize + MAX_CIFS_HDR_SIZE - 4,
684                                         USHRT_MAX));
685         pSMB->req.MaxMpxCount = cpu_to_le16(server->maxReq);
686         pSMB->req.VcNumber = cpu_to_le16(1);
687
688         /* Now no need to set SMBFLG_CASELESS or obsolete CANONICAL PATH */
689
690         /* BB verify whether signing required on neg or just auth frame (and NTLM case) */
691
692         capabilities = CAP_LARGE_FILES | CAP_NT_SMBS | CAP_LEVEL_II_OPLOCKS |
693                         CAP_LARGE_WRITE_X | CAP_LARGE_READ_X;
694
695         if (server->sign)
696                 pSMB->req.hdr.Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
697
698         if (ses->capabilities & CAP_UNICODE) {
699                 pSMB->req.hdr.Flags2 |= SMBFLG2_UNICODE;
700                 capabilities |= CAP_UNICODE;
701         }
702         if (ses->capabilities & CAP_STATUS32) {
703                 pSMB->req.hdr.Flags2 |= SMBFLG2_ERR_STATUS;
704                 capabilities |= CAP_STATUS32;
705         }
706         if (ses->capabilities & CAP_DFS) {
707                 pSMB->req.hdr.Flags2 |= SMBFLG2_DFS;
708                 capabilities |= CAP_DFS;
709         }
710         if (ses->capabilities & CAP_UNIX)
711                 capabilities |= CAP_UNIX;
712
713         return capabilities;
714 }
715
716 static void
717 unicode_oslm_strings(char **pbcc_area, const struct nls_table *nls_cp)
718 {
719         char *bcc_ptr = *pbcc_area;
720         int bytes_ret = 0;
721
722         /* Copy OS version */
723         bytes_ret = cifs_strtoUTF16((__le16 *)bcc_ptr, "Linux version ", 32,
724                                     nls_cp);
725         bcc_ptr += 2 * bytes_ret;
726         bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, init_utsname()->release,
727                                     32, nls_cp);
728         bcc_ptr += 2 * bytes_ret;
729         bcc_ptr += 2; /* trailing null */
730
731         bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, CIFS_NETWORK_OPSYS,
732                                     32, nls_cp);
733         bcc_ptr += 2 * bytes_ret;
734         bcc_ptr += 2; /* trailing null */
735
736         *pbcc_area = bcc_ptr;
737 }
738
739 static void unicode_domain_string(char **pbcc_area, struct cifs_ses *ses,
740                                    const struct nls_table *nls_cp)
741 {
742         char *bcc_ptr = *pbcc_area;
743         int bytes_ret = 0;
744
745         /* copy domain */
746         if (ses->domainName == NULL) {
747                 /*
748                  * Sending null domain better than using a bogus domain name (as
749                  * we did briefly in 2.6.18) since server will use its default
750                  */
751                 *bcc_ptr = 0;
752                 *(bcc_ptr+1) = 0;
753                 bytes_ret = 0;
754         } else
755                 bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, ses->domainName,
756                                             CIFS_MAX_DOMAINNAME_LEN, nls_cp);
757         bcc_ptr += 2 * bytes_ret;
758         bcc_ptr += 2;  /* account for null terminator */
759
760         *pbcc_area = bcc_ptr;
761 }
762
763 static void unicode_ssetup_strings(char **pbcc_area, struct cifs_ses *ses,
764                                    const struct nls_table *nls_cp)
765 {
766         char *bcc_ptr = *pbcc_area;
767         int bytes_ret = 0;
768
769         /* BB FIXME add check that strings less than 335 or will need to send as arrays */
770
771         /* copy user */
772         if (ses->user_name == NULL) {
773                 /* null user mount */
774                 *bcc_ptr = 0;
775                 *(bcc_ptr+1) = 0;
776         } else {
777                 bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, ses->user_name,
778                                             CIFS_MAX_USERNAME_LEN, nls_cp);
779         }
780         bcc_ptr += 2 * bytes_ret;
781         bcc_ptr += 2; /* account for null termination */
782
783         unicode_domain_string(&bcc_ptr, ses, nls_cp);
784         unicode_oslm_strings(&bcc_ptr, nls_cp);
785
786         *pbcc_area = bcc_ptr;
787 }
788
789 static void ascii_ssetup_strings(char **pbcc_area, struct cifs_ses *ses,
790                                  const struct nls_table *nls_cp)
791 {
792         char *bcc_ptr = *pbcc_area;
793         int len;
794
795         /* copy user */
796         /* BB what about null user mounts - check that we do this BB */
797         /* copy user */
798         if (ses->user_name != NULL) {
799                 len = strscpy(bcc_ptr, ses->user_name, CIFS_MAX_USERNAME_LEN);
800                 if (WARN_ON_ONCE(len < 0))
801                         len = CIFS_MAX_USERNAME_LEN - 1;
802                 bcc_ptr += len;
803         }
804         /* else null user mount */
805         *bcc_ptr = 0;
806         bcc_ptr++; /* account for null termination */
807
808         /* copy domain */
809         if (ses->domainName != NULL) {
810                 len = strscpy(bcc_ptr, ses->domainName, CIFS_MAX_DOMAINNAME_LEN);
811                 if (WARN_ON_ONCE(len < 0))
812                         len = CIFS_MAX_DOMAINNAME_LEN - 1;
813                 bcc_ptr += len;
814         } /* else we send a null domain name so server will default to its own domain */
815         *bcc_ptr = 0;
816         bcc_ptr++;
817
818         /* BB check for overflow here */
819
820         strcpy(bcc_ptr, "Linux version ");
821         bcc_ptr += strlen("Linux version ");
822         strcpy(bcc_ptr, init_utsname()->release);
823         bcc_ptr += strlen(init_utsname()->release) + 1;
824
825         strcpy(bcc_ptr, CIFS_NETWORK_OPSYS);
826         bcc_ptr += strlen(CIFS_NETWORK_OPSYS) + 1;
827
828         *pbcc_area = bcc_ptr;
829 }
830
831 static void
832 decode_unicode_ssetup(char **pbcc_area, int bleft, struct cifs_ses *ses,
833                       const struct nls_table *nls_cp)
834 {
835         int len;
836         char *data = *pbcc_area;
837
838         cifs_dbg(FYI, "bleft %d\n", bleft);
839
840         kfree(ses->serverOS);
841         ses->serverOS = cifs_strndup_from_utf16(data, bleft, true, nls_cp);
842         cifs_dbg(FYI, "serverOS=%s\n", ses->serverOS);
843         len = (UniStrnlen((wchar_t *) data, bleft / 2) * 2) + 2;
844         data += len;
845         bleft -= len;
846         if (bleft <= 0)
847                 return;
848
849         kfree(ses->serverNOS);
850         ses->serverNOS = cifs_strndup_from_utf16(data, bleft, true, nls_cp);
851         cifs_dbg(FYI, "serverNOS=%s\n", ses->serverNOS);
852         len = (UniStrnlen((wchar_t *) data, bleft / 2) * 2) + 2;
853         data += len;
854         bleft -= len;
855         if (bleft <= 0)
856                 return;
857
858         kfree(ses->serverDomain);
859         ses->serverDomain = cifs_strndup_from_utf16(data, bleft, true, nls_cp);
860         cifs_dbg(FYI, "serverDomain=%s\n", ses->serverDomain);
861
862         return;
863 }
864
865 static void decode_ascii_ssetup(char **pbcc_area, __u16 bleft,
866                                 struct cifs_ses *ses,
867                                 const struct nls_table *nls_cp)
868 {
869         int len;
870         char *bcc_ptr = *pbcc_area;
871
872         cifs_dbg(FYI, "decode sessetup ascii. bleft %d\n", bleft);
873
874         len = strnlen(bcc_ptr, bleft);
875         if (len >= bleft)
876                 return;
877
878         kfree(ses->serverOS);
879
880         ses->serverOS = kmalloc(len + 1, GFP_KERNEL);
881         if (ses->serverOS) {
882                 memcpy(ses->serverOS, bcc_ptr, len);
883                 ses->serverOS[len] = 0;
884                 if (strncmp(ses->serverOS, "OS/2", 4) == 0)
885                         cifs_dbg(FYI, "OS/2 server\n");
886         }
887
888         bcc_ptr += len + 1;
889         bleft -= len + 1;
890
891         len = strnlen(bcc_ptr, bleft);
892         if (len >= bleft)
893                 return;
894
895         kfree(ses->serverNOS);
896
897         ses->serverNOS = kmalloc(len + 1, GFP_KERNEL);
898         if (ses->serverNOS) {
899                 memcpy(ses->serverNOS, bcc_ptr, len);
900                 ses->serverNOS[len] = 0;
901         }
902
903         bcc_ptr += len + 1;
904         bleft -= len + 1;
905
906         len = strnlen(bcc_ptr, bleft);
907         if (len > bleft)
908                 return;
909
910         /*
911          * No domain field in LANMAN case. Domain is
912          * returned by old servers in the SMB negprot response
913          *
914          * BB For newer servers which do not support Unicode,
915          * but thus do return domain here, we could add parsing
916          * for it later, but it is not very important
917          */
918         cifs_dbg(FYI, "ascii: bytes left %d\n", bleft);
919 }
920 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
921
922 int decode_ntlmssp_challenge(char *bcc_ptr, int blob_len,
923                                     struct cifs_ses *ses)
924 {
925         unsigned int tioffset; /* challenge message target info area */
926         unsigned int tilen; /* challenge message target info area length  */
927         CHALLENGE_MESSAGE *pblob = (CHALLENGE_MESSAGE *)bcc_ptr;
928         __u32 server_flags;
929
930         if (blob_len < sizeof(CHALLENGE_MESSAGE)) {
931                 cifs_dbg(VFS, "challenge blob len %d too small\n", blob_len);
932                 return -EINVAL;
933         }
934
935         if (memcmp(pblob->Signature, "NTLMSSP", 8)) {
936                 cifs_dbg(VFS, "blob signature incorrect %s\n",
937                          pblob->Signature);
938                 return -EINVAL;
939         }
940         if (pblob->MessageType != NtLmChallenge) {
941                 cifs_dbg(VFS, "Incorrect message type %d\n",
942                          pblob->MessageType);
943                 return -EINVAL;
944         }
945
946         server_flags = le32_to_cpu(pblob->NegotiateFlags);
947         cifs_dbg(FYI, "%s: negotiate=0x%08x challenge=0x%08x\n", __func__,
948                  ses->ntlmssp->client_flags, server_flags);
949
950         if ((ses->ntlmssp->client_flags & (NTLMSSP_NEGOTIATE_SEAL | NTLMSSP_NEGOTIATE_SIGN)) &&
951             (!(server_flags & NTLMSSP_NEGOTIATE_56) && !(server_flags & NTLMSSP_NEGOTIATE_128))) {
952                 cifs_dbg(VFS, "%s: requested signing/encryption but server did not return either 56-bit or 128-bit session key size\n",
953                          __func__);
954                 return -EINVAL;
955         }
956         if (!(server_flags & NTLMSSP_NEGOTIATE_NTLM) && !(server_flags & NTLMSSP_NEGOTIATE_EXTENDED_SEC)) {
957                 cifs_dbg(VFS, "%s: server does not seem to support either NTLMv1 or NTLMv2\n", __func__);
958                 return -EINVAL;
959         }
960         if (ses->server->sign && !(server_flags & NTLMSSP_NEGOTIATE_SIGN)) {
961                 cifs_dbg(VFS, "%s: forced packet signing but server does not seem to support it\n",
962                          __func__);
963                 return -EOPNOTSUPP;
964         }
965         if ((ses->ntlmssp->client_flags & NTLMSSP_NEGOTIATE_KEY_XCH) &&
966             !(server_flags & NTLMSSP_NEGOTIATE_KEY_XCH))
967                 pr_warn_once("%s: authentication has been weakened as server does not support key exchange\n",
968                              __func__);
969
970         ses->ntlmssp->server_flags = server_flags;
971
972         memcpy(ses->ntlmssp->cryptkey, pblob->Challenge, CIFS_CRYPTO_KEY_SIZE);
973         /*
974          * In particular we can examine sign flags
975          *
976          * BB spec says that if AvId field of MsvAvTimestamp is populated then
977          * we must set the MIC field of the AUTHENTICATE_MESSAGE
978          */
979
980         tioffset = le32_to_cpu(pblob->TargetInfoArray.BufferOffset);
981         tilen = le16_to_cpu(pblob->TargetInfoArray.Length);
982         if (tioffset > blob_len || tioffset + tilen > blob_len) {
983                 cifs_dbg(VFS, "tioffset + tilen too high %u + %u\n",
984                          tioffset, tilen);
985                 return -EINVAL;
986         }
987         if (tilen) {
988                 kfree_sensitive(ses->auth_key.response);
989                 ses->auth_key.response = kmemdup(bcc_ptr + tioffset, tilen,
990                                                  GFP_KERNEL);
991                 if (!ses->auth_key.response) {
992                         cifs_dbg(VFS, "Challenge target info alloc failure\n");
993                         return -ENOMEM;
994                 }
995                 ses->auth_key.len = tilen;
996         }
997
998         return 0;
999 }
1000
1001 static int size_of_ntlmssp_blob(struct cifs_ses *ses, int base_size)
1002 {
1003         int sz = base_size + ses->auth_key.len
1004                 - CIFS_SESS_KEY_SIZE + CIFS_CPHTXT_SIZE + 2;
1005
1006         if (ses->domainName)
1007                 sz += sizeof(__le16) * strnlen(ses->domainName, CIFS_MAX_DOMAINNAME_LEN);
1008         else
1009                 sz += sizeof(__le16);
1010
1011         if (ses->user_name)
1012                 sz += sizeof(__le16) * strnlen(ses->user_name, CIFS_MAX_USERNAME_LEN);
1013         else
1014                 sz += sizeof(__le16);
1015
1016         if (ses->workstation_name[0])
1017                 sz += sizeof(__le16) * strnlen(ses->workstation_name,
1018                                                ntlmssp_workstation_name_size(ses));
1019         else
1020                 sz += sizeof(__le16);
1021
1022         return sz;
1023 }
1024
1025 static inline void cifs_security_buffer_from_str(SECURITY_BUFFER *pbuf,
1026                                                  char *str_value,
1027                                                  int str_length,
1028                                                  unsigned char *pstart,
1029                                                  unsigned char **pcur,
1030                                                  const struct nls_table *nls_cp)
1031 {
1032         unsigned char *tmp = pstart;
1033         int len;
1034
1035         if (!pbuf)
1036                 return;
1037
1038         if (!pcur)
1039                 pcur = &tmp;
1040
1041         if (!str_value) {
1042                 pbuf->BufferOffset = cpu_to_le32(*pcur - pstart);
1043                 pbuf->Length = 0;
1044                 pbuf->MaximumLength = 0;
1045                 *pcur += sizeof(__le16);
1046         } else {
1047                 len = cifs_strtoUTF16((__le16 *)*pcur,
1048                                       str_value,
1049                                       str_length,
1050                                       nls_cp);
1051                 len *= sizeof(__le16);
1052                 pbuf->BufferOffset = cpu_to_le32(*pcur - pstart);
1053                 pbuf->Length = cpu_to_le16(len);
1054                 pbuf->MaximumLength = cpu_to_le16(len);
1055                 *pcur += len;
1056         }
1057 }
1058
1059 /* BB Move to ntlmssp.c eventually */
1060
1061 int build_ntlmssp_negotiate_blob(unsigned char **pbuffer,
1062                                  u16 *buflen,
1063                                  struct cifs_ses *ses,
1064                                  struct TCP_Server_Info *server,
1065                                  const struct nls_table *nls_cp)
1066 {
1067         int rc = 0;
1068         NEGOTIATE_MESSAGE *sec_blob;
1069         __u32 flags;
1070         unsigned char *tmp;
1071         int len;
1072
1073         len = size_of_ntlmssp_blob(ses, sizeof(NEGOTIATE_MESSAGE));
1074         *pbuffer = kmalloc(len, GFP_KERNEL);
1075         if (!*pbuffer) {
1076                 rc = -ENOMEM;
1077                 cifs_dbg(VFS, "Error %d during NTLMSSP allocation\n", rc);
1078                 *buflen = 0;
1079                 goto setup_ntlm_neg_ret;
1080         }
1081         sec_blob = (NEGOTIATE_MESSAGE *)*pbuffer;
1082
1083         memset(*pbuffer, 0, sizeof(NEGOTIATE_MESSAGE));
1084         memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
1085         sec_blob->MessageType = NtLmNegotiate;
1086
1087         /* BB is NTLMV2 session security format easier to use here? */
1088         flags = NTLMSSP_NEGOTIATE_56 |  NTLMSSP_REQUEST_TARGET |
1089                 NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |
1090                 NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC |
1091                 NTLMSSP_NEGOTIATE_ALWAYS_SIGN | NTLMSSP_NEGOTIATE_SEAL |
1092                 NTLMSSP_NEGOTIATE_SIGN;
1093         if (!server->session_estab || ses->ntlmssp->sesskey_per_smbsess)
1094                 flags |= NTLMSSP_NEGOTIATE_KEY_XCH;
1095
1096         tmp = *pbuffer + sizeof(NEGOTIATE_MESSAGE);
1097         ses->ntlmssp->client_flags = flags;
1098         sec_blob->NegotiateFlags = cpu_to_le32(flags);
1099
1100         /* these fields should be null in negotiate phase MS-NLMP 3.1.5.1.1 */
1101         cifs_security_buffer_from_str(&sec_blob->DomainName,
1102                                       NULL,
1103                                       CIFS_MAX_DOMAINNAME_LEN,
1104                                       *pbuffer, &tmp,
1105                                       nls_cp);
1106
1107         cifs_security_buffer_from_str(&sec_blob->WorkstationName,
1108                                       NULL,
1109                                       CIFS_MAX_WORKSTATION_LEN,
1110                                       *pbuffer, &tmp,
1111                                       nls_cp);
1112
1113         *buflen = tmp - *pbuffer;
1114 setup_ntlm_neg_ret:
1115         return rc;
1116 }
1117
1118 /*
1119  * Build ntlmssp blob with additional fields, such as version,
1120  * supported by modern servers. For safety limit to SMB3 or later
1121  * See notes in MS-NLMP Section 2.2.2.1 e.g.
1122  */
1123 int build_ntlmssp_smb3_negotiate_blob(unsigned char **pbuffer,
1124                                  u16 *buflen,
1125                                  struct cifs_ses *ses,
1126                                  struct TCP_Server_Info *server,
1127                                  const struct nls_table *nls_cp)
1128 {
1129         int rc = 0;
1130         struct negotiate_message *sec_blob;
1131         __u32 flags;
1132         unsigned char *tmp;
1133         int len;
1134
1135         len = size_of_ntlmssp_blob(ses, sizeof(struct negotiate_message));
1136         *pbuffer = kmalloc(len, GFP_KERNEL);
1137         if (!*pbuffer) {
1138                 rc = -ENOMEM;
1139                 cifs_dbg(VFS, "Error %d during NTLMSSP allocation\n", rc);
1140                 *buflen = 0;
1141                 goto setup_ntlm_smb3_neg_ret;
1142         }
1143         sec_blob = (struct negotiate_message *)*pbuffer;
1144
1145         memset(*pbuffer, 0, sizeof(struct negotiate_message));
1146         memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
1147         sec_blob->MessageType = NtLmNegotiate;
1148
1149         /* BB is NTLMV2 session security format easier to use here? */
1150         flags = NTLMSSP_NEGOTIATE_56 |  NTLMSSP_REQUEST_TARGET |
1151                 NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |
1152                 NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC |
1153                 NTLMSSP_NEGOTIATE_ALWAYS_SIGN | NTLMSSP_NEGOTIATE_SEAL |
1154                 NTLMSSP_NEGOTIATE_SIGN | NTLMSSP_NEGOTIATE_VERSION;
1155         if (!server->session_estab || ses->ntlmssp->sesskey_per_smbsess)
1156                 flags |= NTLMSSP_NEGOTIATE_KEY_XCH;
1157
1158         sec_blob->Version.ProductMajorVersion = LINUX_VERSION_MAJOR;
1159         sec_blob->Version.ProductMinorVersion = LINUX_VERSION_PATCHLEVEL;
1160         sec_blob->Version.ProductBuild = cpu_to_le16(SMB3_PRODUCT_BUILD);
1161         sec_blob->Version.NTLMRevisionCurrent = NTLMSSP_REVISION_W2K3;
1162
1163         tmp = *pbuffer + sizeof(struct negotiate_message);
1164         ses->ntlmssp->client_flags = flags;
1165         sec_blob->NegotiateFlags = cpu_to_le32(flags);
1166
1167         /* these fields should be null in negotiate phase MS-NLMP 3.1.5.1.1 */
1168         cifs_security_buffer_from_str(&sec_blob->DomainName,
1169                                       NULL,
1170                                       CIFS_MAX_DOMAINNAME_LEN,
1171                                       *pbuffer, &tmp,
1172                                       nls_cp);
1173
1174         cifs_security_buffer_from_str(&sec_blob->WorkstationName,
1175                                       NULL,
1176                                       CIFS_MAX_WORKSTATION_LEN,
1177                                       *pbuffer, &tmp,
1178                                       nls_cp);
1179
1180         *buflen = tmp - *pbuffer;
1181 setup_ntlm_smb3_neg_ret:
1182         return rc;
1183 }
1184
1185
1186 /* See MS-NLMP 2.2.1.3 */
1187 int build_ntlmssp_auth_blob(unsigned char **pbuffer,
1188                                         u16 *buflen,
1189                                    struct cifs_ses *ses,
1190                                    struct TCP_Server_Info *server,
1191                                    const struct nls_table *nls_cp)
1192 {
1193         int rc;
1194         AUTHENTICATE_MESSAGE *sec_blob;
1195         __u32 flags;
1196         unsigned char *tmp;
1197         int len;
1198
1199         rc = setup_ntlmv2_rsp(ses, nls_cp);
1200         if (rc) {
1201                 cifs_dbg(VFS, "Error %d during NTLMSSP authentication\n", rc);
1202                 *buflen = 0;
1203                 goto setup_ntlmv2_ret;
1204         }
1205
1206         len = size_of_ntlmssp_blob(ses, sizeof(AUTHENTICATE_MESSAGE));
1207         *pbuffer = kmalloc(len, GFP_KERNEL);
1208         if (!*pbuffer) {
1209                 rc = -ENOMEM;
1210                 cifs_dbg(VFS, "Error %d during NTLMSSP allocation\n", rc);
1211                 *buflen = 0;
1212                 goto setup_ntlmv2_ret;
1213         }
1214         sec_blob = (AUTHENTICATE_MESSAGE *)*pbuffer;
1215
1216         memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
1217         sec_blob->MessageType = NtLmAuthenticate;
1218
1219         /* send version information in ntlmssp authenticate also */
1220         flags = ses->ntlmssp->server_flags | NTLMSSP_REQUEST_TARGET |
1221                 NTLMSSP_NEGOTIATE_TARGET_INFO | NTLMSSP_NEGOTIATE_VERSION |
1222                 NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED;
1223
1224         sec_blob->Version.ProductMajorVersion = LINUX_VERSION_MAJOR;
1225         sec_blob->Version.ProductMinorVersion = LINUX_VERSION_PATCHLEVEL;
1226         sec_blob->Version.ProductBuild = cpu_to_le16(SMB3_PRODUCT_BUILD);
1227         sec_blob->Version.NTLMRevisionCurrent = NTLMSSP_REVISION_W2K3;
1228
1229         tmp = *pbuffer + sizeof(AUTHENTICATE_MESSAGE);
1230         sec_blob->NegotiateFlags = cpu_to_le32(flags);
1231
1232         sec_blob->LmChallengeResponse.BufferOffset =
1233                                 cpu_to_le32(sizeof(AUTHENTICATE_MESSAGE));
1234         sec_blob->LmChallengeResponse.Length = 0;
1235         sec_blob->LmChallengeResponse.MaximumLength = 0;
1236
1237         sec_blob->NtChallengeResponse.BufferOffset =
1238                                 cpu_to_le32(tmp - *pbuffer);
1239         if (ses->user_name != NULL) {
1240                 memcpy(tmp, ses->auth_key.response + CIFS_SESS_KEY_SIZE,
1241                                 ses->auth_key.len - CIFS_SESS_KEY_SIZE);
1242                 tmp += ses->auth_key.len - CIFS_SESS_KEY_SIZE;
1243
1244                 sec_blob->NtChallengeResponse.Length =
1245                                 cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);
1246                 sec_blob->NtChallengeResponse.MaximumLength =
1247                                 cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);
1248         } else {
1249                 /*
1250                  * don't send an NT Response for anonymous access
1251                  */
1252                 sec_blob->NtChallengeResponse.Length = 0;
1253                 sec_blob->NtChallengeResponse.MaximumLength = 0;
1254         }
1255
1256         cifs_security_buffer_from_str(&sec_blob->DomainName,
1257                                       ses->domainName,
1258                                       CIFS_MAX_DOMAINNAME_LEN,
1259                                       *pbuffer, &tmp,
1260                                       nls_cp);
1261
1262         cifs_security_buffer_from_str(&sec_blob->UserName,
1263                                       ses->user_name,
1264                                       CIFS_MAX_USERNAME_LEN,
1265                                       *pbuffer, &tmp,
1266                                       nls_cp);
1267
1268         cifs_security_buffer_from_str(&sec_blob->WorkstationName,
1269                                       ses->workstation_name,
1270                                       ntlmssp_workstation_name_size(ses),
1271                                       *pbuffer, &tmp,
1272                                       nls_cp);
1273
1274         if ((ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_KEY_XCH) &&
1275             (!ses->server->session_estab || ses->ntlmssp->sesskey_per_smbsess) &&
1276             !calc_seckey(ses)) {
1277                 memcpy(tmp, ses->ntlmssp->ciphertext, CIFS_CPHTXT_SIZE);
1278                 sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer);
1279                 sec_blob->SessionKey.Length = cpu_to_le16(CIFS_CPHTXT_SIZE);
1280                 sec_blob->SessionKey.MaximumLength =
1281                                 cpu_to_le16(CIFS_CPHTXT_SIZE);
1282                 tmp += CIFS_CPHTXT_SIZE;
1283         } else {
1284                 sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer);
1285                 sec_blob->SessionKey.Length = 0;
1286                 sec_blob->SessionKey.MaximumLength = 0;
1287         }
1288
1289         *buflen = tmp - *pbuffer;
1290 setup_ntlmv2_ret:
1291         return rc;
1292 }
1293
1294 enum securityEnum
1295 cifs_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested)
1296 {
1297         switch (server->negflavor) {
1298         case CIFS_NEGFLAVOR_EXTENDED:
1299                 switch (requested) {
1300                 case Kerberos:
1301                 case RawNTLMSSP:
1302                         return requested;
1303                 case Unspecified:
1304                         if (server->sec_ntlmssp &&
1305                             (global_secflags & CIFSSEC_MAY_NTLMSSP))
1306                                 return RawNTLMSSP;
1307                         if ((server->sec_kerberos || server->sec_mskerberos) &&
1308                             (global_secflags & CIFSSEC_MAY_KRB5))
1309                                 return Kerberos;
1310                         fallthrough;
1311                 default:
1312                         return Unspecified;
1313                 }
1314         case CIFS_NEGFLAVOR_UNENCAP:
1315                 switch (requested) {
1316                 case NTLMv2:
1317                         return requested;
1318                 case Unspecified:
1319                         if (global_secflags & CIFSSEC_MAY_NTLMV2)
1320                                 return NTLMv2;
1321                         break;
1322                 default:
1323                         break;
1324                 }
1325                 fallthrough;
1326         default:
1327                 return Unspecified;
1328         }
1329 }
1330
1331 struct sess_data {
1332         unsigned int xid;
1333         struct cifs_ses *ses;
1334         struct TCP_Server_Info *server;
1335         struct nls_table *nls_cp;
1336         void (*func)(struct sess_data *);
1337         int result;
1338
1339         /* we will send the SMB in three pieces:
1340          * a fixed length beginning part, an optional
1341          * SPNEGO blob (which can be zero length), and a
1342          * last part which will include the strings
1343          * and rest of bcc area. This allows us to avoid
1344          * a large buffer 17K allocation
1345          */
1346         int buf0_type;
1347         struct kvec iov[3];
1348 };
1349
1350 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
1351 static int
1352 sess_alloc_buffer(struct sess_data *sess_data, int wct)
1353 {
1354         int rc;
1355         struct cifs_ses *ses = sess_data->ses;
1356         struct smb_hdr *smb_buf;
1357
1358         rc = small_smb_init_no_tc(SMB_COM_SESSION_SETUP_ANDX, wct, ses,
1359                                   (void **)&smb_buf);
1360
1361         if (rc)
1362                 return rc;
1363
1364         sess_data->iov[0].iov_base = (char *)smb_buf;
1365         sess_data->iov[0].iov_len = be32_to_cpu(smb_buf->smb_buf_length) + 4;
1366         /*
1367          * This variable will be used to clear the buffer
1368          * allocated above in case of any error in the calling function.
1369          */
1370         sess_data->buf0_type = CIFS_SMALL_BUFFER;
1371
1372         /* 2000 big enough to fit max user, domain, NOS name etc. */
1373         sess_data->iov[2].iov_base = kmalloc(2000, GFP_KERNEL);
1374         if (!sess_data->iov[2].iov_base) {
1375                 rc = -ENOMEM;
1376                 goto out_free_smb_buf;
1377         }
1378
1379         return 0;
1380
1381 out_free_smb_buf:
1382         cifs_small_buf_release(smb_buf);
1383         sess_data->iov[0].iov_base = NULL;
1384         sess_data->iov[0].iov_len = 0;
1385         sess_data->buf0_type = CIFS_NO_BUFFER;
1386         return rc;
1387 }
1388
1389 static void
1390 sess_free_buffer(struct sess_data *sess_data)
1391 {
1392         struct kvec *iov = sess_data->iov;
1393
1394         /*
1395          * Zero the session data before freeing, as it might contain sensitive info (keys, etc).
1396          * Note that iov[1] is already freed by caller.
1397          */
1398         if (sess_data->buf0_type != CIFS_NO_BUFFER && iov[0].iov_base)
1399                 memzero_explicit(iov[0].iov_base, iov[0].iov_len);
1400
1401         free_rsp_buf(sess_data->buf0_type, iov[0].iov_base);
1402         sess_data->buf0_type = CIFS_NO_BUFFER;
1403         kfree_sensitive(iov[2].iov_base);
1404 }
1405
1406 static int
1407 sess_establish_session(struct sess_data *sess_data)
1408 {
1409         struct cifs_ses *ses = sess_data->ses;
1410         struct TCP_Server_Info *server = sess_data->server;
1411
1412         cifs_server_lock(server);
1413         if (!server->session_estab) {
1414                 if (server->sign) {
1415                         server->session_key.response =
1416                                 kmemdup(ses->auth_key.response,
1417                                 ses->auth_key.len, GFP_KERNEL);
1418                         if (!server->session_key.response) {
1419                                 cifs_server_unlock(server);
1420                                 return -ENOMEM;
1421                         }
1422                         server->session_key.len =
1423                                                 ses->auth_key.len;
1424                 }
1425                 server->sequence_number = 0x2;
1426                 server->session_estab = true;
1427         }
1428         cifs_server_unlock(server);
1429
1430         cifs_dbg(FYI, "CIFS session established successfully\n");
1431         return 0;
1432 }
1433
1434 static int
1435 sess_sendreceive(struct sess_data *sess_data)
1436 {
1437         int rc;
1438         struct smb_hdr *smb_buf = (struct smb_hdr *) sess_data->iov[0].iov_base;
1439         __u16 count;
1440         struct kvec rsp_iov = { NULL, 0 };
1441
1442         count = sess_data->iov[1].iov_len + sess_data->iov[2].iov_len;
1443         be32_add_cpu(&smb_buf->smb_buf_length, count);
1444         put_bcc(count, smb_buf);
1445
1446         rc = SendReceive2(sess_data->xid, sess_data->ses,
1447                           sess_data->iov, 3 /* num_iovecs */,
1448                           &sess_data->buf0_type,
1449                           CIFS_LOG_ERROR, &rsp_iov);
1450         cifs_small_buf_release(sess_data->iov[0].iov_base);
1451         memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
1452
1453         return rc;
1454 }
1455
1456 static void
1457 sess_auth_ntlmv2(struct sess_data *sess_data)
1458 {
1459         int rc = 0;
1460         struct smb_hdr *smb_buf;
1461         SESSION_SETUP_ANDX *pSMB;
1462         char *bcc_ptr;
1463         struct cifs_ses *ses = sess_data->ses;
1464         struct TCP_Server_Info *server = sess_data->server;
1465         __u32 capabilities;
1466         __u16 bytes_remaining;
1467
1468         /* old style NTLM sessionsetup */
1469         /* wct = 13 */
1470         rc = sess_alloc_buffer(sess_data, 13);
1471         if (rc)
1472                 goto out;
1473
1474         pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1475         bcc_ptr = sess_data->iov[2].iov_base;
1476         capabilities = cifs_ssetup_hdr(ses, server, pSMB);
1477
1478         pSMB->req_no_secext.Capabilities = cpu_to_le32(capabilities);
1479
1480         /* LM2 password would be here if we supported it */
1481         pSMB->req_no_secext.CaseInsensitivePasswordLength = 0;
1482
1483         if (ses->user_name != NULL) {
1484                 /* calculate nlmv2 response and session key */
1485                 rc = setup_ntlmv2_rsp(ses, sess_data->nls_cp);
1486                 if (rc) {
1487                         cifs_dbg(VFS, "Error %d during NTLMv2 authentication\n", rc);
1488                         goto out;
1489                 }
1490
1491                 memcpy(bcc_ptr, ses->auth_key.response + CIFS_SESS_KEY_SIZE,
1492                                 ses->auth_key.len - CIFS_SESS_KEY_SIZE);
1493                 bcc_ptr += ses->auth_key.len - CIFS_SESS_KEY_SIZE;
1494
1495                 /* set case sensitive password length after tilen may get
1496                  * assigned, tilen is 0 otherwise.
1497                  */
1498                 pSMB->req_no_secext.CaseSensitivePasswordLength =
1499                         cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);
1500         } else {
1501                 pSMB->req_no_secext.CaseSensitivePasswordLength = 0;
1502         }
1503
1504         if (ses->capabilities & CAP_UNICODE) {
1505                 if (!IS_ALIGNED(sess_data->iov[0].iov_len, 2)) {
1506                         *bcc_ptr = 0;
1507                         bcc_ptr++;
1508                 }
1509                 unicode_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp);
1510         } else {
1511                 ascii_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp);
1512         }
1513
1514
1515         sess_data->iov[2].iov_len = (long) bcc_ptr -
1516                         (long) sess_data->iov[2].iov_base;
1517
1518         rc = sess_sendreceive(sess_data);
1519         if (rc)
1520                 goto out;
1521
1522         pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1523         smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base;
1524
1525         if (smb_buf->WordCount != 3) {
1526                 rc = -EIO;
1527                 cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount);
1528                 goto out;
1529         }
1530
1531         if (le16_to_cpu(pSMB->resp.Action) & GUEST_LOGIN)
1532                 cifs_dbg(FYI, "Guest login\n"); /* BB mark SesInfo struct? */
1533
1534         ses->Suid = smb_buf->Uid;   /* UID left in wire format (le) */
1535         cifs_dbg(FYI, "UID = %llu\n", ses->Suid);
1536
1537         bytes_remaining = get_bcc(smb_buf);
1538         bcc_ptr = pByteArea(smb_buf);
1539
1540         /* BB check if Unicode and decode strings */
1541         if (bytes_remaining == 0) {
1542                 /* no string area to decode, do nothing */
1543         } else if (smb_buf->Flags2 & SMBFLG2_UNICODE) {
1544                 /* unicode string area must be word-aligned */
1545                 if (!IS_ALIGNED((unsigned long)bcc_ptr - (unsigned long)smb_buf, 2)) {
1546                         ++bcc_ptr;
1547                         --bytes_remaining;
1548                 }
1549                 decode_unicode_ssetup(&bcc_ptr, bytes_remaining, ses,
1550                                       sess_data->nls_cp);
1551         } else {
1552                 decode_ascii_ssetup(&bcc_ptr, bytes_remaining, ses,
1553                                     sess_data->nls_cp);
1554         }
1555
1556         rc = sess_establish_session(sess_data);
1557 out:
1558         sess_data->result = rc;
1559         sess_data->func = NULL;
1560         sess_free_buffer(sess_data);
1561         kfree_sensitive(ses->auth_key.response);
1562         ses->auth_key.response = NULL;
1563 }
1564
1565 #ifdef CONFIG_CIFS_UPCALL
1566 static void
1567 sess_auth_kerberos(struct sess_data *sess_data)
1568 {
1569         int rc = 0;
1570         struct smb_hdr *smb_buf;
1571         SESSION_SETUP_ANDX *pSMB;
1572         char *bcc_ptr;
1573         struct cifs_ses *ses = sess_data->ses;
1574         struct TCP_Server_Info *server = sess_data->server;
1575         __u32 capabilities;
1576         __u16 bytes_remaining;
1577         struct key *spnego_key = NULL;
1578         struct cifs_spnego_msg *msg;
1579         u16 blob_len;
1580
1581         /* extended security */
1582         /* wct = 12 */
1583         rc = sess_alloc_buffer(sess_data, 12);
1584         if (rc)
1585                 goto out;
1586
1587         pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1588         bcc_ptr = sess_data->iov[2].iov_base;
1589         capabilities = cifs_ssetup_hdr(ses, server, pSMB);
1590
1591         spnego_key = cifs_get_spnego_key(ses, server);
1592         if (IS_ERR(spnego_key)) {
1593                 rc = PTR_ERR(spnego_key);
1594                 spnego_key = NULL;
1595                 goto out;
1596         }
1597
1598         msg = spnego_key->payload.data[0];
1599         /*
1600          * check version field to make sure that cifs.upcall is
1601          * sending us a response in an expected form
1602          */
1603         if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
1604                 cifs_dbg(VFS, "incorrect version of cifs.upcall (expected %d but got %d)\n",
1605                          CIFS_SPNEGO_UPCALL_VERSION, msg->version);
1606                 rc = -EKEYREJECTED;
1607                 goto out_put_spnego_key;
1608         }
1609
1610         kfree_sensitive(ses->auth_key.response);
1611         ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
1612                                          GFP_KERNEL);
1613         if (!ses->auth_key.response) {
1614                 cifs_dbg(VFS, "Kerberos can't allocate (%u bytes) memory\n",
1615                          msg->sesskey_len);
1616                 rc = -ENOMEM;
1617                 goto out_put_spnego_key;
1618         }
1619         ses->auth_key.len = msg->sesskey_len;
1620
1621         pSMB->req.hdr.Flags2 |= SMBFLG2_EXT_SEC;
1622         capabilities |= CAP_EXTENDED_SECURITY;
1623         pSMB->req.Capabilities = cpu_to_le32(capabilities);
1624         sess_data->iov[1].iov_base = msg->data + msg->sesskey_len;
1625         sess_data->iov[1].iov_len = msg->secblob_len;
1626         pSMB->req.SecurityBlobLength = cpu_to_le16(sess_data->iov[1].iov_len);
1627
1628         if (ses->capabilities & CAP_UNICODE) {
1629                 /* unicode strings must be word aligned */
1630                 if (!IS_ALIGNED(sess_data->iov[0].iov_len + sess_data->iov[1].iov_len, 2)) {
1631                         *bcc_ptr = 0;
1632                         bcc_ptr++;
1633                 }
1634                 unicode_oslm_strings(&bcc_ptr, sess_data->nls_cp);
1635                 unicode_domain_string(&bcc_ptr, ses, sess_data->nls_cp);
1636         } else {
1637                 /* BB: is this right? */
1638                 ascii_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp);
1639         }
1640
1641         sess_data->iov[2].iov_len = (long) bcc_ptr -
1642                         (long) sess_data->iov[2].iov_base;
1643
1644         rc = sess_sendreceive(sess_data);
1645         if (rc)
1646                 goto out_put_spnego_key;
1647
1648         pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1649         smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base;
1650
1651         if (smb_buf->WordCount != 4) {
1652                 rc = -EIO;
1653                 cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount);
1654                 goto out_put_spnego_key;
1655         }
1656
1657         if (le16_to_cpu(pSMB->resp.Action) & GUEST_LOGIN)
1658                 cifs_dbg(FYI, "Guest login\n"); /* BB mark SesInfo struct? */
1659
1660         ses->Suid = smb_buf->Uid;   /* UID left in wire format (le) */
1661         cifs_dbg(FYI, "UID = %llu\n", ses->Suid);
1662
1663         bytes_remaining = get_bcc(smb_buf);
1664         bcc_ptr = pByteArea(smb_buf);
1665
1666         blob_len = le16_to_cpu(pSMB->resp.SecurityBlobLength);
1667         if (blob_len > bytes_remaining) {
1668                 cifs_dbg(VFS, "bad security blob length %d\n",
1669                                 blob_len);
1670                 rc = -EINVAL;
1671                 goto out_put_spnego_key;
1672         }
1673         bcc_ptr += blob_len;
1674         bytes_remaining -= blob_len;
1675
1676         /* BB check if Unicode and decode strings */
1677         if (bytes_remaining == 0) {
1678                 /* no string area to decode, do nothing */
1679         } else if (smb_buf->Flags2 & SMBFLG2_UNICODE) {
1680                 /* unicode string area must be word-aligned */
1681                 if (!IS_ALIGNED((unsigned long)bcc_ptr - (unsigned long)smb_buf, 2)) {
1682                         ++bcc_ptr;
1683                         --bytes_remaining;
1684                 }
1685                 decode_unicode_ssetup(&bcc_ptr, bytes_remaining, ses,
1686                                       sess_data->nls_cp);
1687         } else {
1688                 decode_ascii_ssetup(&bcc_ptr, bytes_remaining, ses,
1689                                     sess_data->nls_cp);
1690         }
1691
1692         rc = sess_establish_session(sess_data);
1693 out_put_spnego_key:
1694         key_invalidate(spnego_key);
1695         key_put(spnego_key);
1696 out:
1697         sess_data->result = rc;
1698         sess_data->func = NULL;
1699         sess_free_buffer(sess_data);
1700         kfree_sensitive(ses->auth_key.response);
1701         ses->auth_key.response = NULL;
1702 }
1703
1704 #endif /* ! CONFIG_CIFS_UPCALL */
1705
1706 /*
1707  * The required kvec buffers have to be allocated before calling this
1708  * function.
1709  */
1710 static int
1711 _sess_auth_rawntlmssp_assemble_req(struct sess_data *sess_data)
1712 {
1713         SESSION_SETUP_ANDX *pSMB;
1714         struct cifs_ses *ses = sess_data->ses;
1715         struct TCP_Server_Info *server = sess_data->server;
1716         __u32 capabilities;
1717         char *bcc_ptr;
1718
1719         pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1720
1721         capabilities = cifs_ssetup_hdr(ses, server, pSMB);
1722         if ((pSMB->req.hdr.Flags2 & SMBFLG2_UNICODE) == 0) {
1723                 cifs_dbg(VFS, "NTLMSSP requires Unicode support\n");
1724                 return -ENOSYS;
1725         }
1726
1727         pSMB->req.hdr.Flags2 |= SMBFLG2_EXT_SEC;
1728         capabilities |= CAP_EXTENDED_SECURITY;
1729         pSMB->req.Capabilities |= cpu_to_le32(capabilities);
1730
1731         bcc_ptr = sess_data->iov[2].iov_base;
1732         /* unicode strings must be word aligned */
1733         if (!IS_ALIGNED(sess_data->iov[0].iov_len + sess_data->iov[1].iov_len, 2)) {
1734                 *bcc_ptr = 0;
1735                 bcc_ptr++;
1736         }
1737         unicode_oslm_strings(&bcc_ptr, sess_data->nls_cp);
1738
1739         sess_data->iov[2].iov_len = (long) bcc_ptr -
1740                                         (long) sess_data->iov[2].iov_base;
1741
1742         return 0;
1743 }
1744
1745 static void
1746 sess_auth_rawntlmssp_authenticate(struct sess_data *sess_data);
1747
1748 static void
1749 sess_auth_rawntlmssp_negotiate(struct sess_data *sess_data)
1750 {
1751         int rc;
1752         struct smb_hdr *smb_buf;
1753         SESSION_SETUP_ANDX *pSMB;
1754         struct cifs_ses *ses = sess_data->ses;
1755         struct TCP_Server_Info *server = sess_data->server;
1756         __u16 bytes_remaining;
1757         char *bcc_ptr;
1758         unsigned char *ntlmsspblob = NULL;
1759         u16 blob_len;
1760
1761         cifs_dbg(FYI, "rawntlmssp session setup negotiate phase\n");
1762
1763         /*
1764          * if memory allocation is successful, caller of this function
1765          * frees it.
1766          */
1767         ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
1768         if (!ses->ntlmssp) {
1769                 rc = -ENOMEM;
1770                 goto out;
1771         }
1772         ses->ntlmssp->sesskey_per_smbsess = false;
1773
1774         /* wct = 12 */
1775         rc = sess_alloc_buffer(sess_data, 12);
1776         if (rc)
1777                 goto out;
1778
1779         pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1780
1781         /* Build security blob before we assemble the request */
1782         rc = build_ntlmssp_negotiate_blob(&ntlmsspblob,
1783                                      &blob_len, ses, server,
1784                                      sess_data->nls_cp);
1785         if (rc)
1786                 goto out_free_ntlmsspblob;
1787
1788         sess_data->iov[1].iov_len = blob_len;
1789         sess_data->iov[1].iov_base = ntlmsspblob;
1790         pSMB->req.SecurityBlobLength = cpu_to_le16(blob_len);
1791
1792         rc = _sess_auth_rawntlmssp_assemble_req(sess_data);
1793         if (rc)
1794                 goto out_free_ntlmsspblob;
1795
1796         rc = sess_sendreceive(sess_data);
1797
1798         pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1799         smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base;
1800
1801         /* If true, rc here is expected and not an error */
1802         if (sess_data->buf0_type != CIFS_NO_BUFFER &&
1803             smb_buf->Status.CifsError ==
1804                         cpu_to_le32(NT_STATUS_MORE_PROCESSING_REQUIRED))
1805                 rc = 0;
1806
1807         if (rc)
1808                 goto out_free_ntlmsspblob;
1809
1810         cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
1811
1812         if (smb_buf->WordCount != 4) {
1813                 rc = -EIO;
1814                 cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount);
1815                 goto out_free_ntlmsspblob;
1816         }
1817
1818         ses->Suid = smb_buf->Uid;   /* UID left in wire format (le) */
1819         cifs_dbg(FYI, "UID = %llu\n", ses->Suid);
1820
1821         bytes_remaining = get_bcc(smb_buf);
1822         bcc_ptr = pByteArea(smb_buf);
1823
1824         blob_len = le16_to_cpu(pSMB->resp.SecurityBlobLength);
1825         if (blob_len > bytes_remaining) {
1826                 cifs_dbg(VFS, "bad security blob length %d\n",
1827                                 blob_len);
1828                 rc = -EINVAL;
1829                 goto out_free_ntlmsspblob;
1830         }
1831
1832         rc = decode_ntlmssp_challenge(bcc_ptr, blob_len, ses);
1833
1834 out_free_ntlmsspblob:
1835         kfree_sensitive(ntlmsspblob);
1836 out:
1837         sess_free_buffer(sess_data);
1838
1839         if (!rc) {
1840                 sess_data->func = sess_auth_rawntlmssp_authenticate;
1841                 return;
1842         }
1843
1844         /* Else error. Cleanup */
1845         kfree_sensitive(ses->auth_key.response);
1846         ses->auth_key.response = NULL;
1847         kfree_sensitive(ses->ntlmssp);
1848         ses->ntlmssp = NULL;
1849
1850         sess_data->func = NULL;
1851         sess_data->result = rc;
1852 }
1853
1854 static void
1855 sess_auth_rawntlmssp_authenticate(struct sess_data *sess_data)
1856 {
1857         int rc;
1858         struct smb_hdr *smb_buf;
1859         SESSION_SETUP_ANDX *pSMB;
1860         struct cifs_ses *ses = sess_data->ses;
1861         struct TCP_Server_Info *server = sess_data->server;
1862         __u16 bytes_remaining;
1863         char *bcc_ptr;
1864         unsigned char *ntlmsspblob = NULL;
1865         u16 blob_len;
1866
1867         cifs_dbg(FYI, "rawntlmssp session setup authenticate phase\n");
1868
1869         /* wct = 12 */
1870         rc = sess_alloc_buffer(sess_data, 12);
1871         if (rc)
1872                 goto out;
1873
1874         /* Build security blob before we assemble the request */
1875         pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1876         smb_buf = (struct smb_hdr *)pSMB;
1877         rc = build_ntlmssp_auth_blob(&ntlmsspblob,
1878                                         &blob_len, ses, server,
1879                                         sess_data->nls_cp);
1880         if (rc)
1881                 goto out_free_ntlmsspblob;
1882         sess_data->iov[1].iov_len = blob_len;
1883         sess_data->iov[1].iov_base = ntlmsspblob;
1884         pSMB->req.SecurityBlobLength = cpu_to_le16(blob_len);
1885         /*
1886          * Make sure that we tell the server that we are using
1887          * the uid that it just gave us back on the response
1888          * (challenge)
1889          */
1890         smb_buf->Uid = ses->Suid;
1891
1892         rc = _sess_auth_rawntlmssp_assemble_req(sess_data);
1893         if (rc)
1894                 goto out_free_ntlmsspblob;
1895
1896         rc = sess_sendreceive(sess_data);
1897         if (rc)
1898                 goto out_free_ntlmsspblob;
1899
1900         pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1901         smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base;
1902         if (smb_buf->WordCount != 4) {
1903                 rc = -EIO;
1904                 cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount);
1905                 goto out_free_ntlmsspblob;
1906         }
1907
1908         if (le16_to_cpu(pSMB->resp.Action) & GUEST_LOGIN)
1909                 cifs_dbg(FYI, "Guest login\n"); /* BB mark SesInfo struct? */
1910
1911         if (ses->Suid != smb_buf->Uid) {
1912                 ses->Suid = smb_buf->Uid;
1913                 cifs_dbg(FYI, "UID changed! new UID = %llu\n", ses->Suid);
1914         }
1915
1916         bytes_remaining = get_bcc(smb_buf);
1917         bcc_ptr = pByteArea(smb_buf);
1918         blob_len = le16_to_cpu(pSMB->resp.SecurityBlobLength);
1919         if (blob_len > bytes_remaining) {
1920                 cifs_dbg(VFS, "bad security blob length %d\n",
1921                                 blob_len);
1922                 rc = -EINVAL;
1923                 goto out_free_ntlmsspblob;
1924         }
1925         bcc_ptr += blob_len;
1926         bytes_remaining -= blob_len;
1927
1928
1929         /* BB check if Unicode and decode strings */
1930         if (bytes_remaining == 0) {
1931                 /* no string area to decode, do nothing */
1932         } else if (smb_buf->Flags2 & SMBFLG2_UNICODE) {
1933                 /* unicode string area must be word-aligned */
1934                 if (!IS_ALIGNED((unsigned long)bcc_ptr - (unsigned long)smb_buf, 2)) {
1935                         ++bcc_ptr;
1936                         --bytes_remaining;
1937                 }
1938                 decode_unicode_ssetup(&bcc_ptr, bytes_remaining, ses,
1939                                       sess_data->nls_cp);
1940         } else {
1941                 decode_ascii_ssetup(&bcc_ptr, bytes_remaining, ses,
1942                                     sess_data->nls_cp);
1943         }
1944
1945 out_free_ntlmsspblob:
1946         kfree_sensitive(ntlmsspblob);
1947 out:
1948         sess_free_buffer(sess_data);
1949
1950         if (!rc)
1951                 rc = sess_establish_session(sess_data);
1952
1953         /* Cleanup */
1954         kfree_sensitive(ses->auth_key.response);
1955         ses->auth_key.response = NULL;
1956         kfree_sensitive(ses->ntlmssp);
1957         ses->ntlmssp = NULL;
1958
1959         sess_data->func = NULL;
1960         sess_data->result = rc;
1961 }
1962
1963 static int select_sec(struct sess_data *sess_data)
1964 {
1965         int type;
1966         struct cifs_ses *ses = sess_data->ses;
1967         struct TCP_Server_Info *server = sess_data->server;
1968
1969         type = cifs_select_sectype(server, ses->sectype);
1970         cifs_dbg(FYI, "sess setup type %d\n", type);
1971         if (type == Unspecified) {
1972                 cifs_dbg(VFS, "Unable to select appropriate authentication method!\n");
1973                 return -EINVAL;
1974         }
1975
1976         switch (type) {
1977         case NTLMv2:
1978                 sess_data->func = sess_auth_ntlmv2;
1979                 break;
1980         case Kerberos:
1981 #ifdef CONFIG_CIFS_UPCALL
1982                 sess_data->func = sess_auth_kerberos;
1983                 break;
1984 #else
1985                 cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n");
1986                 return -ENOSYS;
1987 #endif /* CONFIG_CIFS_UPCALL */
1988         case RawNTLMSSP:
1989                 sess_data->func = sess_auth_rawntlmssp_negotiate;
1990                 break;
1991         default:
1992                 cifs_dbg(VFS, "secType %d not supported!\n", type);
1993                 return -ENOSYS;
1994         }
1995
1996         return 0;
1997 }
1998
1999 int CIFS_SessSetup(const unsigned int xid, struct cifs_ses *ses,
2000                    struct TCP_Server_Info *server,
2001                    const struct nls_table *nls_cp)
2002 {
2003         int rc = 0;
2004         struct sess_data *sess_data;
2005
2006         if (ses == NULL) {
2007                 WARN(1, "%s: ses == NULL!", __func__);
2008                 return -EINVAL;
2009         }
2010
2011         sess_data = kzalloc(sizeof(struct sess_data), GFP_KERNEL);
2012         if (!sess_data)
2013                 return -ENOMEM;
2014
2015         sess_data->xid = xid;
2016         sess_data->ses = ses;
2017         sess_data->server = server;
2018         sess_data->buf0_type = CIFS_NO_BUFFER;
2019         sess_data->nls_cp = (struct nls_table *) nls_cp;
2020
2021         rc = select_sec(sess_data);
2022         if (rc)
2023                 goto out;
2024
2025         while (sess_data->func)
2026                 sess_data->func(sess_data);
2027
2028         /* Store result before we free sess_data */
2029         rc = sess_data->result;
2030
2031 out:
2032         kfree_sensitive(sess_data);
2033         return rc;
2034 }
2035 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */