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 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the Institute nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 #include "curl_setup.h"
37 #if defined(HAVE_GSSAPI) && !defined(CURL_DISABLE_FTP)
44 #include "curl_base64.h"
46 #include "curl_gssapi.h"
48 #include "curl_krb5.h"
53 /* The last 3 #include files should be in this order */
54 #include "curl_printf.h"
55 #include "curl_memory.h"
58 static CURLcode ftpsend(struct Curl_easy *data, struct connectdata *conn,
61 ssize_t bytes_written;
62 #define SBUF_SIZE 1024
66 CURLcode result = CURLE_OK;
68 enum protection_level data_sec = conn->data_prot;
72 return CURLE_BAD_FUNCTION_ARGUMENT;
74 write_len = strlen(cmd);
75 if(!write_len || write_len > (sizeof(s) -3))
76 return CURLE_BAD_FUNCTION_ARGUMENT;
78 memcpy(&s, cmd, write_len);
79 strcpy(&s[write_len], "\r\n"); /* append a trailing CRLF */
85 conn->data_prot = PROT_CMD;
87 result = Curl_write(data, conn->sock[FIRSTSOCKET], sptr, write_len,
90 DEBUGASSERT(data_sec > PROT_NONE && data_sec < PROT_LAST);
91 conn->data_prot = data_sec;
97 Curl_debug(data, CURLINFO_HEADER_OUT, sptr, (size_t)bytes_written);
99 if(bytes_written != (ssize_t)write_len) {
100 write_len -= bytes_written;
101 sptr += bytes_written;
111 krb5_init(void *app_data)
113 gss_ctx_id_t *context = app_data;
114 /* Make sure our context is initialized for krb5_end. */
115 *context = GSS_C_NO_CONTEXT;
120 krb5_check_prot(void *app_data, int level)
122 (void)app_data; /* unused */
123 if(level == PROT_CONFIDENTIAL)
129 krb5_decode(void *app_data, void *buf, int len,
130 int level UNUSED_PARAM,
131 struct connectdata *conn UNUSED_PARAM)
133 gss_ctx_id_t *context = app_data;
135 gss_buffer_desc enc, dec;
142 maj = gss_unwrap(&min, *context, &enc, &dec, NULL, NULL);
143 if(maj != GSS_S_COMPLETE) {
149 memcpy(buf, dec.value, dec.length);
150 len = curlx_uztosi(dec.length);
151 gss_release_buffer(&min, &dec);
157 krb5_encode(void *app_data, const void *from, int length, int level, void **to)
159 gss_ctx_id_t *context = app_data;
160 gss_buffer_desc dec, enc;
165 /* NOTE that the cast is safe, neither of the krb5, gnu gss and heimdal
166 * libraries modify the input buffer in gss_wrap()
168 dec.value = (void *)from;
170 maj = gss_wrap(&min, *context,
171 level == PROT_PRIVATE,
175 if(maj != GSS_S_COMPLETE)
178 /* malloc a new buffer, in case gss_release_buffer doesn't work as
180 *to = malloc(enc.length);
183 memcpy(*to, enc.value, enc.length);
184 len = curlx_uztosi(enc.length);
185 gss_release_buffer(&min, &enc);
190 krb5_auth(void *app_data, struct Curl_easy *data, struct connectdata *conn)
194 const char *host = conn->host.name;
196 curl_socklen_t l = sizeof(conn->local_addr);
198 const char *service = data->set.str[STRING_SERVICE_NAME] ?
199 data->set.str[STRING_SERVICE_NAME] :
201 const char *srv_host = "host";
202 gss_buffer_desc input_buffer, output_buffer, _gssresp, *gssresp;
205 gss_ctx_id_t *context = app_data;
206 struct gss_channel_bindings_struct chan;
207 size_t base64_sz = 0;
208 struct sockaddr_in **remote_addr =
209 (struct sockaddr_in **)&conn->ip_addr->ai_addr;
212 if(getsockname(conn->sock[FIRSTSOCKET],
213 (struct sockaddr *)&conn->local_addr, &l) < 0)
214 perror("getsockname()");
216 chan.initiator_addrtype = GSS_C_AF_INET;
217 chan.initiator_address.length = l - 4;
218 chan.initiator_address.value = &conn->local_addr.sin_addr.s_addr;
219 chan.acceptor_addrtype = GSS_C_AF_INET;
220 chan.acceptor_address.length = l - 4;
221 chan.acceptor_address.value = &(*remote_addr)->sin_addr.s_addr;
222 chan.application_data.length = 0;
223 chan.application_data.value = NULL;
225 /* this loop will execute twice (once for service, once for host) */
227 /* this really shouldn't be repeated here, but can't help it */
228 if(service == srv_host) {
229 result = ftpsend(data, conn, "AUTH GSSAPI");
233 if(Curl_GetFTPResponse(data, &nread, NULL))
236 if(data->state.buffer[0] != '3')
240 stringp = aprintf("%s@%s", service, host);
244 input_buffer.value = stringp;
245 input_buffer.length = strlen(stringp);
246 maj = gss_import_name(&min, &input_buffer, GSS_C_NT_HOSTBASED_SERVICE,
249 if(maj != GSS_S_COMPLETE) {
250 gss_release_name(&min, &gssname);
251 if(service == srv_host) {
252 failf(data, "Error importing service name %s@%s", service, host);
258 /* We pass NULL as |output_name_type| to avoid a leak. */
259 gss_display_name(&min, gssname, &output_buffer, NULL);
260 infof(data, "Trying against %s", output_buffer.value);
261 gssresp = GSS_C_NO_BUFFER;
262 *context = GSS_C_NO_CONTEXT;
265 /* Release the buffer at each iteration to avoid leaking: the first time
266 we are releasing the memory from gss_display_name. The last item is
267 taken care by a final gss_release_buffer. */
268 gss_release_buffer(&min, &output_buffer);
270 maj = Curl_gss_init_sec_context(data,
282 free(_gssresp.value);
287 infof(data, "Error creating security context");
292 if(output_buffer.length) {
295 result = Curl_base64_encode((char *)output_buffer.value,
296 output_buffer.length, &p, &base64_sz);
298 infof(data, "base64-encoding: %s", curl_easy_strerror(result));
303 cmd = aprintf("ADAT %s", p);
305 result = ftpsend(data, conn, cmd);
307 result = CURLE_OUT_OF_MEMORY;
317 if(Curl_GetFTPResponse(data, &nread, NULL)) {
322 if(data->state.buffer[0] != '2' && data->state.buffer[0] != '3') {
323 infof(data, "Server didn't accept auth data");
328 _gssresp.value = NULL; /* make sure it is initialized */
329 p = data->state.buffer + 4;
330 p = strstr(p, "ADAT=");
332 result = Curl_base64_decode(p + 5,
333 (unsigned char **)&_gssresp.value,
336 failf(data, "base64-decoding: %s", curl_easy_strerror(result));
344 } while(maj == GSS_S_CONTINUE_NEEDED);
346 gss_release_name(&min, &gssname);
347 gss_release_buffer(&min, &output_buffer);
350 free(_gssresp.value);
352 if(ret == AUTH_OK || service == srv_host)
360 static void krb5_end(void *app_data)
363 gss_ctx_id_t *context = app_data;
364 if(*context != GSS_C_NO_CONTEXT) {
365 OM_uint32 maj = gss_delete_sec_context(&min, context, GSS_C_NO_BUFFER);
367 DEBUGASSERT(maj == GSS_S_COMPLETE);
371 static const struct Curl_sec_client_mech Curl_krb5_client_mech = {
373 sizeof(gss_ctx_id_t),
383 static const struct {
384 enum protection_level level;
387 { PROT_CLEAR, "clear" },
388 { PROT_SAFE, "safe" },
389 { PROT_CONFIDENTIAL, "confidential" },
390 { PROT_PRIVATE, "private" }
393 static enum protection_level
394 name_to_level(const char *name)
397 for(i = 0; i < (int)sizeof(level_names)/(int)sizeof(level_names[0]); i++)
398 if(curl_strequal(name, level_names[i].name))
399 return level_names[i].level;
403 /* Convert a protocol |level| to its char representation.
404 We take an int to catch programming mistakes. */
405 static char level_to_char(int level)
412 case PROT_CONFIDENTIAL:
419 /* Those 2 cases should not be reached! */
423 /* Default to the most secure alternative. */
427 /* Send an FTP command defined by |message| and the optional arguments. The
428 function returns the ftp_code. If an error occurs, -1 is returned. */
429 static int ftp_send_command(struct Curl_easy *data, const char *message, ...)
434 char print_buffer[50];
436 va_start(args, message);
437 mvsnprintf(print_buffer, sizeof(print_buffer), message, args);
440 if(ftpsend(data, data->conn, print_buffer)) {
444 if(Curl_GetFTPResponse(data, &nread, &ftp_code))
448 (void)nread; /* Unused */
452 /* Read |len| from the socket |fd| and store it in |to|. Return a CURLcode
453 saying whether an error occurred or CURLE_OK if |len| was read. */
455 socket_read(curl_socket_t fd, void *to, size_t len)
462 result = Curl_read_plain(fd, to_p, len, &nread);
468 if(result == CURLE_AGAIN)
477 /* Write |len| bytes from the buffer |to| to the socket |fd|. Return a
478 CURLcode saying whether an error occurred or CURLE_OK if |len| was
481 socket_write(struct Curl_easy *data, curl_socket_t fd, const void *to,
484 const char *to_p = to;
489 result = Curl_write_plain(data, fd, to_p, len, &written);
495 if(result == CURLE_AGAIN)
503 static CURLcode read_data(struct connectdata *conn,
505 struct krb5buffer *buf)
510 result = socket_read(fd, &len, sizeof(len));
515 /* only realloc if there was a length */
517 buf->data = Curl_saferealloc(buf->data, len);
519 if(!len || !buf->data)
520 return CURLE_OUT_OF_MEMORY;
522 result = socket_read(fd, buf->data, len);
525 buf->size = conn->mech->decode(conn->app_data, buf->data, len,
526 conn->data_prot, conn);
532 buffer_read(struct krb5buffer *buf, void *data, size_t len)
534 if(buf->size - buf->index < len)
535 len = buf->size - buf->index;
536 memcpy(data, (char *)buf->data + buf->index, len);
541 /* Matches Curl_recv signature */
542 static ssize_t sec_recv(struct Curl_easy *data, int sockindex,
543 char *buffer, size_t len, CURLcode *err)
546 size_t total_read = 0;
547 struct connectdata *conn = data->conn;
548 curl_socket_t fd = conn->sock[sockindex];
552 /* Handle clear text response. */
553 if(conn->sec_complete == 0 || conn->data_prot == PROT_CLEAR)
554 return sread(fd, buffer, len);
556 if(conn->in_buffer.eof_flag) {
557 conn->in_buffer.eof_flag = 0;
561 bytes_read = buffer_read(&conn->in_buffer, buffer, len);
563 total_read += bytes_read;
564 buffer += bytes_read;
567 if(read_data(conn, fd, &conn->in_buffer))
569 if(conn->in_buffer.size == 0) {
571 conn->in_buffer.eof_flag = 1;
574 bytes_read = buffer_read(&conn->in_buffer, buffer, len);
576 total_read += bytes_read;
577 buffer += bytes_read;
582 /* Send |length| bytes from |from| to the |fd| socket taking care of encoding
583 and negotiating with the server. |from| can be NULL. */
584 static void do_sec_send(struct Curl_easy *data, struct connectdata *conn,
585 curl_socket_t fd, const char *from, int length)
587 int bytes, htonl_bytes; /* 32-bit integers for htonl */
592 enum protection_level prot_level = conn->data_prot;
593 bool iscmd = (prot_level == PROT_CMD)?TRUE:FALSE;
595 DEBUGASSERT(prot_level > PROT_NONE && prot_level < PROT_LAST);
598 if(!strncmp(from, "PASS ", 5) || !strncmp(from, "ACCT ", 5))
599 prot_level = PROT_PRIVATE;
601 prot_level = conn->command_prot;
603 bytes = conn->mech->encode(conn->app_data, from, length, prot_level,
605 if(!buffer || bytes <= 0)
609 error = Curl_base64_encode(buffer, curlx_sitouz(bytes),
610 &cmd_buffer, &cmd_size);
616 static const char *enc = "ENC ";
617 static const char *mic = "MIC ";
618 if(prot_level == PROT_PRIVATE)
619 socket_write(data, fd, enc, 4);
621 socket_write(data, fd, mic, 4);
623 socket_write(data, fd, cmd_buffer, cmd_size);
624 socket_write(data, fd, "\r\n", 2);
625 infof(data, "Send: %s%s", prot_level == PROT_PRIVATE?enc:mic,
631 htonl_bytes = htonl(bytes);
632 socket_write(data, fd, &htonl_bytes, sizeof(htonl_bytes));
633 socket_write(data, fd, buffer, curlx_sitouz(bytes));
638 static ssize_t sec_write(struct Curl_easy *data, struct connectdata *conn,
639 curl_socket_t fd, const char *buffer, size_t length)
641 ssize_t tx = 0, len = conn->buffer_size;
646 if(length < (size_t)len)
649 do_sec_send(data, conn, fd, buffer, curlx_sztosi(len));
657 /* Matches Curl_send signature */
658 static ssize_t sec_send(struct Curl_easy *data, int sockindex,
659 const void *buffer, size_t len, CURLcode *err)
661 struct connectdata *conn = data->conn;
662 curl_socket_t fd = conn->sock[sockindex];
664 return sec_write(data, conn, fd, buffer, len);
667 int Curl_sec_read_msg(struct Curl_easy *data, struct connectdata *conn,
668 char *buffer, enum protection_level level)
670 /* decoded_len should be size_t or ssize_t but conn->mech->decode returns an
675 size_t decoded_sz = 0;
681 /* not initialized, return error */
684 DEBUGASSERT(level > PROT_NONE && level < PROT_LAST);
686 error = Curl_base64_decode(buffer + 4, (unsigned char **)&buf, &decoded_sz);
687 if(error || decoded_sz == 0)
690 if(decoded_sz > (size_t)INT_MAX) {
694 decoded_len = curlx_uztosi(decoded_sz);
696 decoded_len = conn->mech->decode(conn->app_data, buf, decoded_len,
698 if(decoded_len <= 0) {
704 buf[decoded_len] = '\n';
705 Curl_debug(data, CURLINFO_HEADER_IN, buf, decoded_len + 1);
708 buf[decoded_len] = '\0';
710 /* suspiciously short */
714 /* safe to ignore return code */
715 (void)sscanf(buf, "%d", &ret_code);
717 if(buf[decoded_len - 1] == '\n')
718 buf[decoded_len - 1] = '\0';
724 static int sec_set_protection_level(struct Curl_easy *data)
727 struct connectdata *conn = data->conn;
728 enum protection_level level = conn->request_data_prot;
730 DEBUGASSERT(level > PROT_NONE && level < PROT_LAST);
732 if(!conn->sec_complete) {
733 infof(data, "Trying to change the protection level after the"
734 " completion of the data exchange.");
738 /* Bail out if we try to set up the same level */
739 if(conn->data_prot == level)
744 unsigned int buffer_size = 1 << 20; /* 1048576 */
746 code = ftp_send_command(data, "PBSZ %u", buffer_size);
751 failf(data, "Failed to set the protection's buffer size.");
754 conn->buffer_size = buffer_size;
756 pbsz = strstr(data->state.buffer, "PBSZ=");
758 /* ignore return code, use default value if it fails */
759 (void)sscanf(pbsz, "PBSZ=%u", &buffer_size);
760 if(buffer_size < conn->buffer_size)
761 conn->buffer_size = buffer_size;
765 /* Now try to negotiate the protection level. */
766 code = ftp_send_command(data, "PROT %c", level_to_char(level));
772 failf(data, "Failed to set the protection level.");
776 conn->data_prot = level;
777 if(level == PROT_PRIVATE)
778 conn->command_prot = level;
784 Curl_sec_request_prot(struct connectdata *conn, const char *level)
786 enum protection_level l = name_to_level(level);
789 DEBUGASSERT(l > PROT_NONE && l < PROT_LAST);
790 conn->request_data_prot = l;
794 static CURLcode choose_mech(struct Curl_easy *data, struct connectdata *conn)
797 void *tmp_allocation;
798 const struct Curl_sec_client_mech *mech = &Curl_krb5_client_mech;
800 tmp_allocation = realloc(conn->app_data, mech->size);
801 if(!tmp_allocation) {
802 failf(data, "Failed realloc of size %zu", mech->size);
804 return CURLE_OUT_OF_MEMORY;
806 conn->app_data = tmp_allocation;
809 ret = mech->init(conn->app_data);
811 infof(data, "Failed initialization for %s. Skipping it.",
813 return CURLE_FAILED_INIT;
817 infof(data, "Trying mechanism %s...", mech->name);
818 ret = ftp_send_command(data, "AUTH %s", mech->name);
820 return CURLE_COULDNT_CONNECT;
825 infof(data, "Mechanism %s is not supported by the server (server "
826 "returned ftp code: 504).", mech->name);
829 infof(data, "Mechanism %s was rejected by the server (server returned "
830 "ftp code: 534).", mech->name);
834 infof(data, "server does not support the security extensions");
835 return CURLE_USE_SSL_FAILED;
839 return CURLE_LOGIN_DENIED;
843 ret = mech->auth(conn->app_data, data, conn);
845 if(ret != AUTH_CONTINUE) {
847 /* Mechanism has dumped the error to stderr, don't error here. */
848 return CURLE_USE_SSL_FAILED;
850 DEBUGASSERT(ret == AUTH_OK);
853 conn->sec_complete = 1;
854 conn->recv[FIRSTSOCKET] = sec_recv;
855 conn->send[FIRSTSOCKET] = sec_send;
856 conn->recv[SECONDARYSOCKET] = sec_recv;
857 conn->send[SECONDARYSOCKET] = sec_send;
858 conn->command_prot = PROT_SAFE;
859 /* Set the requested protection level */
861 (void)sec_set_protection_level(data);
868 Curl_sec_login(struct Curl_easy *data, struct connectdata *conn)
870 return choose_mech(data, conn);
875 Curl_sec_end(struct connectdata *conn)
877 if(conn->mech && conn->mech->end)
878 conn->mech->end(conn->app_data);
879 free(conn->app_data);
880 conn->app_data = NULL;
881 if(conn->in_buffer.data) {
882 free(conn->in_buffer.data);
883 conn->in_buffer.data = NULL;
884 conn->in_buffer.size = 0;
885 conn->in_buffer.index = 0;
886 conn->in_buffer.eof_flag = 0;
888 conn->sec_complete = 0;
889 conn->data_prot = PROT_CLEAR;
893 #endif /* HAVE_GSSAPI && !CURL_DISABLE_FTP */