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