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