2 Unix SMB/CIFS implementation.
3 SMB client generic functions
4 Copyright (C) Andrew Tridgell 1994-1998
5 Copyright (C) Jeremy Allison 2007.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "libsmb/libsmb.h"
23 #include "../lib/util/tevent_ntstatus.h"
24 #include "smb_signing.h"
25 #include "async_smb.h"
27 /*******************************************************************
28 Setup the word count and byte count for a client smb message.
29 ********************************************************************/
31 int cli_set_message(char *buf,int num_words,int num_bytes,bool zero)
33 if (zero && (num_words || num_bytes)) {
34 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
36 SCVAL(buf,smb_wct,num_words);
37 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
38 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
39 return (smb_size + num_words*2 + num_bytes);
42 /****************************************************************************
43 Change the timeout (in milliseconds).
44 ****************************************************************************/
46 unsigned int cli_set_timeout(struct cli_state *cli, unsigned int timeout)
48 unsigned int old_timeout = cli->timeout;
49 cli->timeout = timeout;
53 /****************************************************************************
54 Change the port number used to call on.
55 ****************************************************************************/
57 void cli_set_port(struct cli_state *cli, int port)
62 /****************************************************************************
63 convenience routine to find if we negotiated ucs2
64 ****************************************************************************/
66 bool cli_ucs2(struct cli_state *cli)
68 return ((cli->capabilities & CAP_UNICODE) != 0);
72 /****************************************************************************
73 Read an smb from a fd ignoring all keepalive packets.
74 The timeout is in milliseconds
76 This is exactly the same as receive_smb except that it never returns
77 a session keepalive packet (just as receive_smb used to do).
78 receive_smb was changed to return keepalives as the oplock processing means this call
79 should never go into a blocking read.
80 ****************************************************************************/
82 static ssize_t client_receive_smb(struct cli_state *cli, size_t maxlen)
89 set_smb_read_error(&cli->smb_rw_error, SMB_READ_OK);
91 status = receive_smb_raw(cli->fd, cli->inbuf, cli->bufsize,
92 cli->timeout, maxlen, &len);
93 if (!NT_STATUS_IS_OK(status)) {
94 DEBUG(10,("client_receive_smb failed\n"));
97 if (NT_STATUS_EQUAL(status, NT_STATUS_END_OF_FILE)) {
98 set_smb_read_error(&cli->smb_rw_error,
103 if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) {
104 set_smb_read_error(&cli->smb_rw_error,
109 set_smb_read_error(&cli->smb_rw_error, SMB_READ_ERROR);
114 * I don't believe len can be < 0 with NT_STATUS_OK
115 * returned above, but this check doesn't hurt. JRA.
118 if ((ssize_t)len < 0) {
122 /* Ignore session keepalive packets. */
123 if(CVAL(cli->inbuf,0) != SMBkeepalive) {
128 if (cli_encryption_on(cli)) {
129 NTSTATUS status = cli_decrypt_message(cli);
130 if (!NT_STATUS_IS_OK(status)) {
131 DEBUG(0, ("SMB decryption failed on incoming packet! Error %s\n",
133 cli->smb_rw_error = SMB_READ_BAD_DECRYPT;
138 show_msg(cli->inbuf);
142 static bool cli_state_set_seqnum(struct cli_state *cli, uint16_t mid, uint32_t seqnum)
144 struct cli_state_seqnum *c;
146 for (c = cli->seqnum; c; c = c->next) {
153 c = talloc_zero(cli, struct cli_state_seqnum);
160 c->persistent = false;
161 DLIST_ADD_END(cli->seqnum, c, struct cli_state_seqnum *);
166 bool cli_state_seqnum_persistent(struct cli_state *cli,
169 struct cli_state_seqnum *c;
171 for (c = cli->seqnum; c; c = c->next) {
173 c->persistent = true;
181 bool cli_state_seqnum_remove(struct cli_state *cli,
184 struct cli_state_seqnum *c;
186 for (c = cli->seqnum; c; c = c->next) {
188 DLIST_REMOVE(cli->seqnum, c);
197 static uint32_t cli_state_get_seqnum(struct cli_state *cli, uint16_t mid)
199 struct cli_state_seqnum *c;
201 for (c = cli->seqnum; c; c = c->next) {
203 uint32_t seqnum = c->seqnum;
204 if (!c->persistent) {
205 DLIST_REMOVE(cli->seqnum, c);
215 /****************************************************************************
217 ****************************************************************************/
219 bool cli_receive_smb(struct cli_state *cli)
225 /* fd == -1 causes segfaults -- Tom (tom@ninja.nl) */
230 len = client_receive_smb(cli, 0);
233 /* it might be an oplock break request */
234 if (!(CVAL(cli->inbuf, smb_flg) & FLAG_REPLY) &&
235 CVAL(cli->inbuf,smb_com) == SMBlockingX &&
236 SVAL(cli->inbuf,smb_vwv6) == 0 &&
237 SVAL(cli->inbuf,smb_vwv7) == 0) {
238 if (cli->oplock_handler) {
239 int fnum = SVAL(cli->inbuf,smb_vwv2);
240 unsigned char level = CVAL(cli->inbuf,smb_vwv3+1);
241 if (!NT_STATUS_IS_OK(cli->oplock_handler(cli, fnum, level))) {
245 /* try to prevent loops */
246 SCVAL(cli->inbuf,smb_com,0xFF);
251 /* If the server is not responding, note that now */
254 * only log if the connection should still be open and not when
255 * the connection was closed due to a dropped ip message
258 char addr[INET6_ADDRSTRLEN];
259 print_sockaddr(addr, sizeof(addr), &cli->dest_ss);
260 DEBUG(0, ("Receiving SMB: Server %s stopped responding\n",
268 mid = SVAL(cli->inbuf,smb_mid);
269 seqnum = cli_state_get_seqnum(cli, mid);
271 if (!cli_check_sign_mac(cli, cli->inbuf, seqnum+1)) {
273 * If we get a signature failure in sessionsetup, then
274 * the server sometimes just reflects the sent signature
275 * back to us. Detect this and allow the upper layer to
276 * retrieve the correct Windows error message.
278 if (CVAL(cli->outbuf,smb_com) == SMBsesssetupX &&
279 (smb_len(cli->inbuf) > (smb_ss_field + 8 - 4)) &&
280 (SVAL(cli->inbuf,smb_flg2) & FLAGS2_SMB_SECURITY_SIGNATURES) &&
281 memcmp(&cli->outbuf[smb_ss_field],&cli->inbuf[smb_ss_field],8) == 0 &&
285 * Reflected signature on login error.
286 * Set bad sig but don't close fd.
288 cli->smb_rw_error = SMB_READ_BAD_SIG;
292 DEBUG(0, ("SMB Signature verification failed on incoming packet!\n"));
293 cli->smb_rw_error = SMB_READ_BAD_SIG;
301 static ssize_t write_socket(int fd, const char *buf, size_t len)
305 DEBUG(6,("write_socket(%d,%d)\n",fd,(int)len));
306 ret = write_data(fd,buf,len);
308 DEBUG(6,("write_socket(%d,%d) wrote %d\n",fd,(int)len,(int)ret));
310 DEBUG(0,("write_socket: Error writing %d bytes to socket %d: ERRNO = %s\n",
311 (int)len, fd, strerror(errno) ));
316 /****************************************************************************
318 ****************************************************************************/
320 bool cli_send_smb(struct cli_state *cli)
325 char *buf_out = cli->outbuf;
326 bool enc_on = cli_encryption_on(cli);
329 /* fd == -1 causes segfaults -- Tom (tom@ninja.nl) */
333 cli_calculate_sign_mac(cli, cli->outbuf, &seqnum);
335 if (!cli_state_set_seqnum(cli, cli->mid, seqnum)) {
336 DEBUG(0,("Failed to store mid[%u]/seqnum[%u]\n",
337 (unsigned int)cli->mid,
338 (unsigned int)seqnum));
343 NTSTATUS status = cli_encrypt_message(cli, cli->outbuf,
345 if (!NT_STATUS_IS_OK(status)) {
348 cli->smb_rw_error = SMB_WRITE_ERROR;
349 DEBUG(0,("Error in encrypting client message. Error %s\n",
350 nt_errstr(status) ));
355 len = smb_len(buf_out) + 4;
357 while (nwritten < len) {
358 ret = write_socket(cli->fd,buf_out+nwritten,len - nwritten);
361 cli_free_enc_buffer(cli, buf_out);
365 cli->smb_rw_error = SMB_WRITE_ERROR;
366 DEBUG(0,("Error writing %d bytes to client. %d (%s)\n",
367 (int)len,(int)ret, strerror(errno) ));
374 cli_free_enc_buffer(cli, buf_out);
377 /* Increment the mid so we can tell between responses. */
384 /****************************************************************************
385 Setup basics in a outgoing packet.
386 ****************************************************************************/
388 void cli_setup_packet_buf(struct cli_state *cli, char *buf)
392 SIVAL(buf,smb_rcls,0);
393 SSVAL(buf,smb_pid,cli->pid);
394 memset(buf+smb_pidhigh, 0, 12);
395 SSVAL(buf,smb_uid,cli->vuid);
396 SSVAL(buf,smb_mid,cli->mid);
398 if (cli->protocol <= PROTOCOL_CORE) {
402 if (cli->case_sensitive) {
403 SCVAL(buf,smb_flg,0x0);
405 /* Default setting, case insensitive. */
406 SCVAL(buf,smb_flg,0x8);
408 flags2 = FLAGS2_LONG_PATH_COMPONENTS;
409 if (cli->capabilities & CAP_UNICODE)
410 flags2 |= FLAGS2_UNICODE_STRINGS;
411 if ((cli->capabilities & CAP_DFS) && cli->dfsroot)
412 flags2 |= FLAGS2_DFS_PATHNAMES;
413 if (cli->capabilities & CAP_STATUS32)
414 flags2 |= FLAGS2_32_BIT_ERROR_CODES;
416 flags2 |= FLAGS2_EXTENDED_SECURITY;
417 SSVAL(buf,smb_flg2, flags2);
420 /****************************************************************************
421 Initialize Domain, user or password.
422 ****************************************************************************/
424 NTSTATUS cli_set_domain(struct cli_state *cli, const char *domain)
426 TALLOC_FREE(cli->domain);
427 cli->domain = talloc_strdup(cli, domain ? domain : "");
428 if (cli->domain == NULL) {
429 return NT_STATUS_NO_MEMORY;
434 NTSTATUS cli_set_username(struct cli_state *cli, const char *username)
436 TALLOC_FREE(cli->user_name);
437 cli->user_name = talloc_strdup(cli, username ? username : "");
438 if (cli->user_name == NULL) {
439 return NT_STATUS_NO_MEMORY;
444 NTSTATUS cli_set_password(struct cli_state *cli, const char *password)
446 TALLOC_FREE(cli->password);
448 /* Password can be NULL. */
450 cli->password = talloc_strdup(cli, password);
451 if (cli->password == NULL) {
452 return NT_STATUS_NO_MEMORY;
455 /* Use zero NTLMSSP hashes and session key. */
456 cli->password = NULL;
462 /****************************************************************************
463 Initialise credentials of a client structure.
464 ****************************************************************************/
466 NTSTATUS cli_init_creds(struct cli_state *cli, const char *username, const char *domain, const char *password)
468 NTSTATUS status = cli_set_username(cli, username);
469 if (!NT_STATUS_IS_OK(status)) {
472 status = cli_set_domain(cli, domain);
473 if (!NT_STATUS_IS_OK(status)) {
476 DEBUG(10,("cli_init_creds: user %s domain %s\n", cli->user_name, cli->domain));
478 return cli_set_password(cli, password);
481 /****************************************************************************
482 Initialise a client structure. Always returns a talloc'ed struct.
483 Set the signing state (used from the command line).
484 ****************************************************************************/
486 struct cli_state *cli_initialise_ex(int signing_state)
488 struct cli_state *cli = NULL;
489 bool allow_smb_signing = false;
490 bool mandatory_signing = false;
492 /* Check the effective uid - make sure we are not setuid */
493 if (is_setuid_root()) {
494 DEBUG(0,("libsmb based programs must *NOT* be setuid root.\n"));
498 cli = TALLOC_ZERO_P(NULL, struct cli_state);
503 cli->dfs_mountpoint = talloc_strdup(cli, "");
504 if (!cli->dfs_mountpoint) {
510 cli->pid = (uint16)sys_getpid();
512 cli->vuid = UID_FIELD_INVALID;
513 cli->protocol = PROTOCOL_NT1;
514 cli->timeout = 20000; /* Timeout is in milliseconds. */
515 cli->bufsize = CLI_BUFFER_SIZE+4;
516 cli->max_xmit = cli->bufsize;
517 cli->outbuf = (char *)SMB_MALLOC(cli->bufsize+SAFETY_MARGIN);
519 cli->inbuf = (char *)SMB_MALLOC(cli->bufsize+SAFETY_MARGIN);
520 cli->oplock_handler = cli_oplock_ack;
521 cli->case_sensitive = false;
522 cli->smb_rw_error = SMB_READ_OK;
524 cli->use_spnego = lp_client_use_spnego();
526 cli->capabilities = CAP_UNICODE | CAP_STATUS32 | CAP_DFS;
528 /* Set the CLI_FORCE_DOSERR environment variable to test
529 client routines using DOS errors instead of STATUS32
530 ones. This intended only as a temporary hack. */
531 if (getenv("CLI_FORCE_DOSERR"))
532 cli->force_dos_errors = true;
534 if (lp_client_signing()) {
535 allow_smb_signing = true;
538 if (lp_client_signing() == Required) {
539 mandatory_signing = true;
542 if (signing_state != Undefined) {
543 allow_smb_signing = true;
546 if (signing_state == false) {
547 allow_smb_signing = false;
548 mandatory_signing = false;
551 if (signing_state == Required) {
552 mandatory_signing = true;
555 if (!cli->outbuf || !cli->inbuf)
558 memset(cli->outbuf, 0, cli->bufsize);
559 memset(cli->inbuf, 0, cli->bufsize);
561 /* initialise signing */
562 cli->signing_state = smb_signing_init(cli,
565 if (!cli->signing_state) {
569 cli->outgoing = tevent_queue_create(cli, "cli_outgoing");
570 if (cli->outgoing == NULL) {
575 cli->initialised = 1;
579 /* Clean up after malloc() error */
583 SAFE_FREE(cli->inbuf);
584 SAFE_FREE(cli->outbuf);
589 struct cli_state *cli_initialise(void)
591 return cli_initialise_ex(Undefined);
594 /****************************************************************************
595 Close all pipes open on this session.
596 ****************************************************************************/
598 void cli_nt_pipes_close(struct cli_state *cli)
600 while (cli->pipe_list != NULL) {
602 * No TALLOC_FREE here!
604 talloc_free(cli->pipe_list);
608 /****************************************************************************
609 Shutdown a client structure.
610 ****************************************************************************/
612 static void _cli_shutdown(struct cli_state *cli)
614 cli_nt_pipes_close(cli);
617 * tell our peer to free his resources. Wihtout this, when an
618 * application attempts to do a graceful shutdown and calls
619 * smbc_free_context() to clean up all connections, some connections
620 * can remain active on the peer end, until some (long) timeout period
621 * later. This tree disconnect forces the peer to clean up, since the
622 * connection will be going away.
624 * Also, do not do tree disconnect when cli->smb_rw_error is SMB_DO_NOT_DO_TDIS
625 * the only user for this so far is smbmount which passes opened connection
626 * down to kernel's smbfs module.
628 if ( (cli->cnum != (uint16)-1) && (cli->smb_rw_error != SMB_DO_NOT_DO_TDIS ) ) {
632 SAFE_FREE(cli->outbuf);
633 SAFE_FREE(cli->inbuf);
635 data_blob_free(&cli->secblob);
636 data_blob_free(&cli->user_session_key);
642 cli->smb_rw_error = SMB_READ_OK;
645 * Need to free pending first, they remove themselves
647 while (cli->pending) {
648 talloc_free(cli->pending[0]);
653 void cli_shutdown(struct cli_state *cli)
655 struct cli_state *cli_head;
659 DLIST_HEAD(cli, cli_head);
660 if (cli_head == cli) {
662 * head of a DFS list, shutdown all subsidiary DFS
665 struct cli_state *p, *next;
667 for (p = cli_head->next; p; p = next) {
669 DLIST_REMOVE(cli_head, p);
673 DLIST_REMOVE(cli_head, cli);
679 /****************************************************************************
680 Set socket options on a open connection.
681 ****************************************************************************/
683 void cli_sockopt(struct cli_state *cli, const char *options)
685 set_socket_options(cli->fd, options);
688 /****************************************************************************
689 Set the PID to use for smb messages. Return the old pid.
690 ****************************************************************************/
692 uint16 cli_setpid(struct cli_state *cli, uint16 pid)
694 uint16 ret = cli->pid;
699 /****************************************************************************
700 Set the case sensitivity flag on the packets. Returns old state.
701 ****************************************************************************/
703 bool cli_set_case_sensitive(struct cli_state *cli, bool case_sensitive)
705 bool ret = cli->case_sensitive;
706 cli->case_sensitive = case_sensitive;
710 struct cli_echo_state {
716 static void cli_echo_done(struct tevent_req *subreq);
718 struct tevent_req *cli_echo_send(TALLOC_CTX *mem_ctx, struct event_context *ev,
719 struct cli_state *cli, uint16_t num_echos,
722 struct tevent_req *req, *subreq;
723 struct cli_echo_state *state;
725 req = tevent_req_create(mem_ctx, &state, struct cli_echo_state);
729 SSVAL(state->vwv, 0, num_echos);
731 state->num_echos = num_echos;
733 subreq = cli_smb_send(state, ev, cli, SMBecho, 0, 1, state->vwv,
734 data.length, data.data);
735 if (subreq == NULL) {
738 tevent_req_set_callback(subreq, cli_echo_done, req);
745 static void cli_echo_done(struct tevent_req *subreq)
747 struct tevent_req *req = tevent_req_callback_data(
748 subreq, struct tevent_req);
749 struct cli_echo_state *state = tevent_req_data(
750 req, struct cli_echo_state);
756 status = cli_smb_recv(subreq, state, &inbuf, 0, NULL, NULL,
758 if (!NT_STATUS_IS_OK(status)) {
759 tevent_req_nterror(req, status);
762 if ((num_bytes != state->data.length)
763 || (memcmp(bytes, state->data.data, num_bytes) != 0)) {
764 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
768 state->num_echos -=1;
769 if (state->num_echos == 0) {
770 tevent_req_done(req);
774 if (!cli_smb_req_set_pending(subreq)) {
775 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
781 * Get the result out from an echo request
782 * @param[in] req The async_req from cli_echo_send
783 * @retval Did the server reply correctly?
786 NTSTATUS cli_echo_recv(struct tevent_req *req)
788 return tevent_req_simple_recv_ntstatus(req);
792 * @brief Send/Receive SMBEcho requests
793 * @param[in] mem_ctx The memory context to put the async_req on
794 * @param[in] ev The event context that will call us back
795 * @param[in] cli The connection to send the echo to
796 * @param[in] num_echos How many times do we want to get the reply?
797 * @param[in] data The data we want to get back
798 * @retval Did the server reply correctly?
801 NTSTATUS cli_echo(struct cli_state *cli, uint16_t num_echos, DATA_BLOB data)
803 TALLOC_CTX *frame = talloc_stackframe();
804 struct event_context *ev;
805 struct tevent_req *req;
806 NTSTATUS status = NT_STATUS_OK;
808 if (cli_has_async_calls(cli)) {
810 * Can't use sync call while an async call is in flight
812 status = NT_STATUS_INVALID_PARAMETER;
816 ev = event_context_init(frame);
818 status = NT_STATUS_NO_MEMORY;
822 req = cli_echo_send(frame, ev, cli, num_echos, data);
824 status = NT_STATUS_NO_MEMORY;
828 if (!tevent_req_poll(req, ev)) {
829 status = map_nt_error_from_unix(errno);
833 status = cli_echo_recv(req);
836 if (!NT_STATUS_IS_OK(status)) {
837 cli_set_error(cli, status);
843 * Is the SMB command able to hold an AND_X successor
844 * @param[in] cmd The SMB command in question
845 * @retval Can we add a chained request after "cmd"?
847 bool is_andx_req(uint8_t cmd)
867 NTSTATUS cli_smb(TALLOC_CTX *mem_ctx, struct cli_state *cli,
868 uint8_t smb_command, uint8_t additional_flags,
869 uint8_t wct, uint16_t *vwv,
870 uint32_t num_bytes, const uint8_t *bytes,
871 struct tevent_req **result_parent,
872 uint8_t min_wct, uint8_t *pwct, uint16_t **pvwv,
873 uint32_t *pnum_bytes, uint8_t **pbytes)
875 struct tevent_context *ev;
876 struct tevent_req *req = NULL;
877 NTSTATUS status = NT_STATUS_NO_MEMORY;
879 if (cli_has_async_calls(cli)) {
880 return NT_STATUS_INVALID_PARAMETER;
882 ev = tevent_context_init(mem_ctx);
886 req = cli_smb_send(mem_ctx, ev, cli, smb_command, additional_flags,
887 wct, vwv, num_bytes, bytes);
891 if (!tevent_req_poll_ntstatus(req, ev, &status)) {
894 status = cli_smb_recv(req, NULL, NULL, min_wct, pwct, pvwv,
898 if (NT_STATUS_IS_OK(status) && (result_parent != NULL)) {
899 *result_parent = req;