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