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