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