1 /* GSSAPI/krb5 support for FTP - loosely based on old krb4.c
3 * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska Högskolan
4 * (Royal Institute of Technology, Stockholm, Sweden).
5 * Copyright (c) 2004 - 2022 Daniel Stenberg
8 * SPDX-License-Identifier: BSD-3-Clause
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
21 * 3. Neither the name of the Institute nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 #include "curl_setup.h"
39 #if defined(HAVE_GSSAPI) && !defined(CURL_DISABLE_FTP)
46 #include "curl_base64.h"
48 #include "curl_gssapi.h"
50 #include "curl_krb5.h"
55 /* The last 3 #include files should be in this order */
56 #include "curl_printf.h"
57 #include "curl_memory.h"
60 static CURLcode ftpsend(struct Curl_easy *data, struct connectdata *conn,
63 ssize_t bytes_written;
64 #define SBUF_SIZE 1024
68 CURLcode result = CURLE_OK;
70 enum protection_level data_sec = conn->data_prot;
74 return CURLE_BAD_FUNCTION_ARGUMENT;
76 write_len = strlen(cmd);
77 if(!write_len || write_len > (sizeof(s) -3))
78 return CURLE_BAD_FUNCTION_ARGUMENT;
80 memcpy(&s, cmd, write_len);
81 strcpy(&s[write_len], "\r\n"); /* append a trailing CRLF */
87 conn->data_prot = PROT_CMD;
89 result = Curl_write(data, conn->sock[FIRSTSOCKET], sptr, write_len,
92 DEBUGASSERT(data_sec > PROT_NONE && data_sec < PROT_LAST);
93 conn->data_prot = data_sec;
99 Curl_debug(data, CURLINFO_HEADER_OUT, sptr, (size_t)bytes_written);
101 if(bytes_written != (ssize_t)write_len) {
102 write_len -= bytes_written;
103 sptr += bytes_written;
113 krb5_init(void *app_data)
115 gss_ctx_id_t *context = app_data;
116 /* Make sure our context is initialized for krb5_end. */
117 *context = GSS_C_NO_CONTEXT;
122 krb5_check_prot(void *app_data, int level)
124 (void)app_data; /* unused */
125 if(level == PROT_CONFIDENTIAL)
131 krb5_decode(void *app_data, void *buf, int len,
132 int level UNUSED_PARAM,
133 struct connectdata *conn UNUSED_PARAM)
135 gss_ctx_id_t *context = app_data;
137 gss_buffer_desc enc, dec;
144 maj = gss_unwrap(&min, *context, &enc, &dec, NULL, NULL);
145 if(maj != GSS_S_COMPLETE)
148 memcpy(buf, dec.value, dec.length);
149 len = curlx_uztosi(dec.length);
150 gss_release_buffer(&min, &dec);
156 krb5_encode(void *app_data, const void *from, int length, int level, void **to)
158 gss_ctx_id_t *context = app_data;
159 gss_buffer_desc dec, enc;
164 /* NOTE that the cast is safe, neither of the krb5, gnu gss and heimdal
165 * libraries modify the input buffer in gss_wrap()
167 dec.value = (void *)from;
169 maj = gss_wrap(&min, *context,
170 level == PROT_PRIVATE,
174 if(maj != GSS_S_COMPLETE)
177 /* malloc a new buffer, in case gss_release_buffer doesn't work as
179 *to = malloc(enc.length);
182 memcpy(*to, enc.value, enc.length);
183 len = curlx_uztosi(enc.length);
184 gss_release_buffer(&min, &enc);
189 krb5_auth(void *app_data, struct Curl_easy *data, struct connectdata *conn)
193 const char *host = conn->host.name;
195 curl_socklen_t l = sizeof(conn->local_addr);
197 const char *service = data->set.str[STRING_SERVICE_NAME] ?
198 data->set.str[STRING_SERVICE_NAME] :
200 const char *srv_host = "host";
201 gss_buffer_desc input_buffer, output_buffer, _gssresp, *gssresp;
204 gss_ctx_id_t *context = app_data;
205 struct gss_channel_bindings_struct chan;
206 size_t base64_sz = 0;
207 struct sockaddr_in **remote_addr =
208 (struct sockaddr_in **)&conn->ip_addr->ai_addr;
211 if(getsockname(conn->sock[FIRSTSOCKET],
212 (struct sockaddr *)&conn->local_addr, &l) < 0)
213 perror("getsockname()");
215 chan.initiator_addrtype = GSS_C_AF_INET;
216 chan.initiator_address.length = l - 4;
217 chan.initiator_address.value = &conn->local_addr.sin_addr.s_addr;
218 chan.acceptor_addrtype = GSS_C_AF_INET;
219 chan.acceptor_address.length = l - 4;
220 chan.acceptor_address.value = &(*remote_addr)->sin_addr.s_addr;
221 chan.application_data.length = 0;
222 chan.application_data.value = NULL;
224 /* this loop will execute twice (once for service, once for host) */
226 /* this really shouldn't be repeated here, but can't help it */
227 if(service == srv_host) {
228 result = ftpsend(data, conn, "AUTH GSSAPI");
232 if(Curl_GetFTPResponse(data, &nread, NULL))
235 if(data->state.buffer[0] != '3')
239 stringp = aprintf("%s@%s", service, host);
243 input_buffer.value = stringp;
244 input_buffer.length = strlen(stringp);
245 maj = gss_import_name(&min, &input_buffer, GSS_C_NT_HOSTBASED_SERVICE,
248 if(maj != GSS_S_COMPLETE) {
249 gss_release_name(&min, &gssname);
250 if(service == srv_host) {
251 failf(data, "Error importing service name %s@%s", service, host);
257 /* We pass NULL as |output_name_type| to avoid a leak. */
258 gss_display_name(&min, gssname, &output_buffer, NULL);
259 infof(data, "Trying against %s", output_buffer.value);
260 gssresp = GSS_C_NO_BUFFER;
261 *context = GSS_C_NO_CONTEXT;
264 /* Release the buffer at each iteration to avoid leaking: the first time
265 we are releasing the memory from gss_display_name. The last item is
266 taken care by a final gss_release_buffer. */
267 gss_release_buffer(&min, &output_buffer);
269 maj = Curl_gss_init_sec_context(data,
281 free(_gssresp.value);
286 infof(data, "Error creating security context");
291 if(output_buffer.length) {
294 result = Curl_base64_encode((char *)output_buffer.value,
295 output_buffer.length, &p, &base64_sz);
297 infof(data, "base64-encoding: %s", curl_easy_strerror(result));
302 cmd = aprintf("ADAT %s", p);
304 result = ftpsend(data, conn, cmd);
306 result = CURLE_OUT_OF_MEMORY;
316 if(Curl_GetFTPResponse(data, &nread, NULL)) {
321 if(data->state.buffer[0] != '2' && data->state.buffer[0] != '3') {
322 infof(data, "Server didn't accept auth data");
327 _gssresp.value = NULL; /* make sure it is initialized */
328 p = data->state.buffer + 4;
329 p = strstr(p, "ADAT=");
331 result = Curl_base64_decode(p + 5,
332 (unsigned char **)&_gssresp.value,
335 failf(data, "base64-decoding: %s", curl_easy_strerror(result));
343 } while(maj == GSS_S_CONTINUE_NEEDED);
345 gss_release_name(&min, &gssname);
346 gss_release_buffer(&min, &output_buffer);
349 free(_gssresp.value);
351 if(ret == AUTH_OK || service == srv_host)
359 static void krb5_end(void *app_data)
362 gss_ctx_id_t *context = app_data;
363 if(*context != GSS_C_NO_CONTEXT) {
364 OM_uint32 maj = gss_delete_sec_context(&min, context, GSS_C_NO_BUFFER);
366 DEBUGASSERT(maj == GSS_S_COMPLETE);
370 static const struct Curl_sec_client_mech Curl_krb5_client_mech = {
372 sizeof(gss_ctx_id_t),
382 static const struct {
383 enum protection_level level;
386 { PROT_CLEAR, "clear" },
387 { PROT_SAFE, "safe" },
388 { PROT_CONFIDENTIAL, "confidential" },
389 { PROT_PRIVATE, "private" }
392 static enum protection_level
393 name_to_level(const char *name)
396 for(i = 0; i < (int)sizeof(level_names)/(int)sizeof(level_names[0]); i++)
397 if(curl_strequal(name, level_names[i].name))
398 return level_names[i].level;
402 /* Convert a protocol |level| to its char representation.
403 We take an int to catch programming mistakes. */
404 static char level_to_char(int level)
411 case PROT_CONFIDENTIAL:
418 /* Those 2 cases should not be reached! */
422 /* Default to the most secure alternative. */
426 /* Send an FTP command defined by |message| and the optional arguments. The
427 function returns the ftp_code. If an error occurs, -1 is returned. */
428 static int ftp_send_command(struct Curl_easy *data, const char *message, ...)
433 char print_buffer[50];
435 va_start(args, message);
436 mvsnprintf(print_buffer, sizeof(print_buffer), message, args);
439 if(ftpsend(data, data->conn, print_buffer)) {
443 if(Curl_GetFTPResponse(data, &nread, &ftp_code))
447 (void)nread; /* Unused */
451 /* Read |len| from the socket |fd| and store it in |to|. Return a CURLcode
452 saying whether an error occurred or CURLE_OK if |len| was read. */
454 socket_read(curl_socket_t fd, void *to, size_t len)
461 result = Curl_read_plain(fd, to_p, len, &nread);
467 if(result == CURLE_AGAIN)
476 /* Write |len| bytes from the buffer |to| to the socket |fd|. Return a
477 CURLcode saying whether an error occurred or CURLE_OK if |len| was
480 socket_write(struct Curl_easy *data, curl_socket_t fd, const void *to,
483 const char *to_p = to;
488 result = Curl_write_plain(data, fd, to_p, len, &written);
494 if(result == CURLE_AGAIN)
502 static CURLcode read_data(struct connectdata *conn,
504 struct krb5buffer *buf)
510 result = socket_read(fd, &len, sizeof(len));
515 /* only realloc if there was a length */
517 if(len > CURL_MAX_INPUT_LENGTH)
520 buf->data = Curl_saferealloc(buf->data, len);
522 if(!len || !buf->data)
523 return CURLE_OUT_OF_MEMORY;
525 result = socket_read(fd, buf->data, len);
528 nread = conn->mech->decode(conn->app_data, buf->data, len,
529 conn->data_prot, conn);
531 return CURLE_RECV_ERROR;
532 buf->size = (size_t)nread;
538 buffer_read(struct krb5buffer *buf, void *data, size_t len)
540 if(buf->size - buf->index < len)
541 len = buf->size - buf->index;
542 memcpy(data, (char *)buf->data + buf->index, len);
547 /* Matches Curl_recv signature */
548 static ssize_t sec_recv(struct Curl_easy *data, int sockindex,
549 char *buffer, size_t len, CURLcode *err)
552 size_t total_read = 0;
553 struct connectdata *conn = data->conn;
554 curl_socket_t fd = conn->sock[sockindex];
558 /* Handle clear text response. */
559 if(conn->sec_complete == 0 || conn->data_prot == PROT_CLEAR)
560 return sread(fd, buffer, len);
562 if(conn->in_buffer.eof_flag) {
563 conn->in_buffer.eof_flag = 0;
567 bytes_read = buffer_read(&conn->in_buffer, buffer, len);
569 total_read += bytes_read;
570 buffer += bytes_read;
573 if(read_data(conn, fd, &conn->in_buffer))
575 if(conn->in_buffer.size == 0) {
577 conn->in_buffer.eof_flag = 1;
580 bytes_read = buffer_read(&conn->in_buffer, buffer, len);
582 total_read += bytes_read;
583 buffer += bytes_read;
588 /* Send |length| bytes from |from| to the |fd| socket taking care of encoding
589 and negotiating with the server. |from| can be NULL. */
590 static void do_sec_send(struct Curl_easy *data, struct connectdata *conn,
591 curl_socket_t fd, const char *from, int length)
593 int bytes, htonl_bytes; /* 32-bit integers for htonl */
598 enum protection_level prot_level = conn->data_prot;
599 bool iscmd = (prot_level == PROT_CMD)?TRUE:FALSE;
601 DEBUGASSERT(prot_level > PROT_NONE && prot_level < PROT_LAST);
604 if(!strncmp(from, "PASS ", 5) || !strncmp(from, "ACCT ", 5))
605 prot_level = PROT_PRIVATE;
607 prot_level = conn->command_prot;
609 bytes = conn->mech->encode(conn->app_data, from, length, prot_level,
611 if(!buffer || bytes <= 0)
615 error = Curl_base64_encode(buffer, curlx_sitouz(bytes),
616 &cmd_buffer, &cmd_size);
622 static const char *enc = "ENC ";
623 static const char *mic = "MIC ";
624 if(prot_level == PROT_PRIVATE)
625 socket_write(data, fd, enc, 4);
627 socket_write(data, fd, mic, 4);
629 socket_write(data, fd, cmd_buffer, cmd_size);
630 socket_write(data, fd, "\r\n", 2);
631 infof(data, "Send: %s%s", prot_level == PROT_PRIVATE?enc:mic,
637 htonl_bytes = htonl(bytes);
638 socket_write(data, fd, &htonl_bytes, sizeof(htonl_bytes));
639 socket_write(data, fd, buffer, curlx_sitouz(bytes));
644 static ssize_t sec_write(struct Curl_easy *data, struct connectdata *conn,
645 curl_socket_t fd, const char *buffer, size_t length)
647 ssize_t tx = 0, len = conn->buffer_size;
652 if(length < (size_t)len)
655 do_sec_send(data, conn, fd, buffer, curlx_sztosi(len));
663 /* Matches Curl_send signature */
664 static ssize_t sec_send(struct Curl_easy *data, int sockindex,
665 const void *buffer, size_t len, CURLcode *err)
667 struct connectdata *conn = data->conn;
668 curl_socket_t fd = conn->sock[sockindex];
670 return sec_write(data, conn, fd, buffer, len);
673 int Curl_sec_read_msg(struct Curl_easy *data, struct connectdata *conn,
674 char *buffer, enum protection_level level)
676 /* decoded_len should be size_t or ssize_t but conn->mech->decode returns an
681 size_t decoded_sz = 0;
687 /* not initialized, return error */
690 DEBUGASSERT(level > PROT_NONE && level < PROT_LAST);
692 error = Curl_base64_decode(buffer + 4, (unsigned char **)&buf, &decoded_sz);
693 if(error || decoded_sz == 0)
696 if(decoded_sz > (size_t)INT_MAX) {
700 decoded_len = curlx_uztosi(decoded_sz);
702 decoded_len = conn->mech->decode(conn->app_data, buf, decoded_len,
704 if(decoded_len <= 0) {
710 buf[decoded_len] = '\n';
711 Curl_debug(data, CURLINFO_HEADER_IN, buf, decoded_len + 1);
714 buf[decoded_len] = '\0';
716 /* suspiciously short */
720 /* safe to ignore return code */
721 (void)sscanf(buf, "%d", &ret_code);
723 if(buf[decoded_len - 1] == '\n')
724 buf[decoded_len - 1] = '\0';
730 static int sec_set_protection_level(struct Curl_easy *data)
733 struct connectdata *conn = data->conn;
734 enum protection_level level = conn->request_data_prot;
736 DEBUGASSERT(level > PROT_NONE && level < PROT_LAST);
738 if(!conn->sec_complete) {
739 infof(data, "Trying to change the protection level after the"
740 " completion of the data exchange.");
744 /* Bail out if we try to set up the same level */
745 if(conn->data_prot == level)
750 unsigned int buffer_size = 1 << 20; /* 1048576 */
752 code = ftp_send_command(data, "PBSZ %u", buffer_size);
757 failf(data, "Failed to set the protection's buffer size.");
760 conn->buffer_size = buffer_size;
762 pbsz = strstr(data->state.buffer, "PBSZ=");
764 /* ignore return code, use default value if it fails */
765 (void)sscanf(pbsz, "PBSZ=%u", &buffer_size);
766 if(buffer_size < conn->buffer_size)
767 conn->buffer_size = buffer_size;
771 /* Now try to negotiate the protection level. */
772 code = ftp_send_command(data, "PROT %c", level_to_char(level));
778 failf(data, "Failed to set the protection level.");
782 conn->data_prot = level;
783 if(level == PROT_PRIVATE)
784 conn->command_prot = level;
790 Curl_sec_request_prot(struct connectdata *conn, const char *level)
792 enum protection_level l = name_to_level(level);
795 DEBUGASSERT(l > PROT_NONE && l < PROT_LAST);
796 conn->request_data_prot = l;
800 static CURLcode choose_mech(struct Curl_easy *data, struct connectdata *conn)
803 void *tmp_allocation;
804 const struct Curl_sec_client_mech *mech = &Curl_krb5_client_mech;
806 tmp_allocation = realloc(conn->app_data, mech->size);
807 if(!tmp_allocation) {
808 failf(data, "Failed realloc of size %zu", mech->size);
810 return CURLE_OUT_OF_MEMORY;
812 conn->app_data = tmp_allocation;
815 ret = mech->init(conn->app_data);
817 infof(data, "Failed initialization for %s. Skipping it.",
819 return CURLE_FAILED_INIT;
823 infof(data, "Trying mechanism %s...", mech->name);
824 ret = ftp_send_command(data, "AUTH %s", mech->name);
826 return CURLE_COULDNT_CONNECT;
831 infof(data, "Mechanism %s is not supported by the server (server "
832 "returned ftp code: 504).", mech->name);
835 infof(data, "Mechanism %s was rejected by the server (server returned "
836 "ftp code: 534).", mech->name);
840 infof(data, "server does not support the security extensions");
841 return CURLE_USE_SSL_FAILED;
845 return CURLE_LOGIN_DENIED;
849 ret = mech->auth(conn->app_data, data, conn);
851 if(ret != AUTH_CONTINUE) {
853 /* Mechanism has dumped the error to stderr, don't error here. */
854 return CURLE_USE_SSL_FAILED;
856 DEBUGASSERT(ret == AUTH_OK);
859 conn->sec_complete = 1;
860 conn->recv[FIRSTSOCKET] = sec_recv;
861 conn->send[FIRSTSOCKET] = sec_send;
862 conn->recv[SECONDARYSOCKET] = sec_recv;
863 conn->send[SECONDARYSOCKET] = sec_send;
864 conn->command_prot = PROT_SAFE;
865 /* Set the requested protection level */
867 (void)sec_set_protection_level(data);
874 Curl_sec_login(struct Curl_easy *data, struct connectdata *conn)
876 return choose_mech(data, conn);
881 Curl_sec_end(struct connectdata *conn)
883 if(conn->mech && conn->mech->end)
884 conn->mech->end(conn->app_data);
885 free(conn->app_data);
886 conn->app_data = NULL;
887 if(conn->in_buffer.data) {
888 free(conn->in_buffer.data);
889 conn->in_buffer.data = NULL;
890 conn->in_buffer.size = 0;
891 conn->in_buffer.index = 0;
892 conn->in_buffer.eof_flag = 0;
894 conn->sec_complete = 0;
895 conn->data_prot = PROT_CLEAR;
899 #endif /* HAVE_GSSAPI && !CURL_DISABLE_FTP */