xref: /curl/lib/krb5.c (revision c41e9cc1)
1 /* GSSAPI/krb5 support for FTP - loosely based on old krb4.c
2  *
3  * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska Högskolan
4  * (Royal Institute of Technology, Stockholm, Sweden).
5  * Copyright (C) Daniel Stenberg
6  * All rights reserved.
7  *
8  * SPDX-License-Identifier: BSD-3-Clause
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  *
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.
20  *
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.
24  *
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
35  * SUCH DAMAGE.  */
36 
37 #include "curl_setup.h"
38 
39 #if defined(HAVE_GSSAPI) && !defined(CURL_DISABLE_FTP)
40 
41 #ifdef HAVE_NETDB_H
42 #include <netdb.h>
43 #endif
44 #ifdef HAVE_ARPA_INET_H
45 #include <arpa/inet.h>
46 #endif
47 
48 #include "urldata.h"
49 #include "cfilters.h"
50 #include "cf-socket.h"
51 #include "curl_base64.h"
52 #include "ftp.h"
53 #include "curl_gssapi.h"
54 #include "sendf.h"
55 #include "transfer.h"
56 #include "curl_krb5.h"
57 #include "warnless.h"
58 #include "strcase.h"
59 #include "strdup.h"
60 
61 /* The last 3 #include files should be in this order */
62 #include "curl_printf.h"
63 #include "curl_memory.h"
64 #include "memdebug.h"
65 
ftpsend(struct Curl_easy * data,struct connectdata * conn,const char * cmd)66 static CURLcode ftpsend(struct Curl_easy *data, struct connectdata *conn,
67                         const char *cmd)
68 {
69   size_t bytes_written;
70 #define SBUF_SIZE 1024
71   char s[SBUF_SIZE];
72   size_t write_len;
73   char *sptr = s;
74   CURLcode result = CURLE_OK;
75 #ifdef HAVE_GSSAPI
76   unsigned char data_sec = conn->data_prot;
77 #endif
78 
79   DEBUGASSERT(cmd);
80 
81   write_len = strlen(cmd);
82   if(!write_len || write_len > (sizeof(s) -3))
83     return CURLE_BAD_FUNCTION_ARGUMENT;
84 
85   memcpy(&s, cmd, write_len);
86   strcpy(&s[write_len], "\r\n"); /* append a trailing CRLF */
87   write_len += 2;
88   bytes_written = 0;
89 
90   for(;;) {
91 #ifdef HAVE_GSSAPI
92     conn->data_prot = PROT_CMD;
93 #endif
94     result = Curl_xfer_send(data, sptr, write_len, FALSE, &bytes_written);
95 #ifdef HAVE_GSSAPI
96     DEBUGASSERT(data_sec > PROT_NONE && data_sec < PROT_LAST);
97     conn->data_prot = data_sec;
98 #endif
99 
100     if(result)
101       break;
102 
103     Curl_debug(data, CURLINFO_HEADER_OUT, sptr, bytes_written);
104 
105     if(bytes_written != write_len) {
106       write_len -= bytes_written;
107       sptr += bytes_written;
108     }
109     else
110       break;
111   }
112 
113   return result;
114 }
115 
116 static int
krb5_init(void * app_data)117 krb5_init(void *app_data)
118 {
119   gss_ctx_id_t *context = app_data;
120   /* Make sure our context is initialized for krb5_end. */
121   *context = GSS_C_NO_CONTEXT;
122   return 0;
123 }
124 
125 static int
krb5_check_prot(void * app_data,int level)126 krb5_check_prot(void *app_data, int level)
127 {
128   (void)app_data; /* unused */
129   if(level == PROT_CONFIDENTIAL)
130     return -1;
131   return 0;
132 }
133 
134 static int
krb5_decode(void * app_data,void * buf,int len,int level UNUSED_PARAM,struct connectdata * conn UNUSED_PARAM)135 krb5_decode(void *app_data, void *buf, int len,
136             int level UNUSED_PARAM,
137             struct connectdata *conn UNUSED_PARAM)
138 {
139   gss_ctx_id_t *context = app_data;
140   OM_uint32 maj, min;
141   gss_buffer_desc enc, dec;
142 
143   (void)level;
144   (void)conn;
145 
146   enc.value = buf;
147   enc.length = len;
148   maj = gss_unwrap(&min, *context, &enc, &dec, NULL, NULL);
149   if(maj != GSS_S_COMPLETE)
150     return -1;
151 
152   memcpy(buf, dec.value, dec.length);
153   len = curlx_uztosi(dec.length);
154   gss_release_buffer(&min, &dec);
155 
156   return len;
157 }
158 
159 static int
krb5_encode(void * app_data,const void * from,int length,int level,void ** to)160 krb5_encode(void *app_data, const void *from, int length, int level, void **to)
161 {
162   gss_ctx_id_t *context = app_data;
163   gss_buffer_desc dec, enc;
164   OM_uint32 maj, min;
165   int state;
166   int len;
167 
168   /* NOTE that the cast is safe, neither of the krb5, gnu gss and heimdal
169    * libraries modify the input buffer in gss_wrap()
170    */
171   dec.value = (void *)from;
172   dec.length = (size_t)length;
173   maj = gss_wrap(&min, *context,
174                  level == PROT_PRIVATE,
175                  GSS_C_QOP_DEFAULT,
176                  &dec, &state, &enc);
177 
178   if(maj != GSS_S_COMPLETE)
179     return -1;
180 
181   /* malloc a new buffer, in case gss_release_buffer does not work as
182      expected */
183   *to = malloc(enc.length);
184   if(!*to)
185     return -1;
186   memcpy(*to, enc.value, enc.length);
187   len = curlx_uztosi(enc.length);
188   gss_release_buffer(&min, &enc);
189   return len;
190 }
191 
192 static int
krb5_auth(void * app_data,struct Curl_easy * data,struct connectdata * conn)193 krb5_auth(void *app_data, struct Curl_easy *data, struct connectdata *conn)
194 {
195   int ret = AUTH_OK;
196   char *p;
197   const char *host = conn->host.name;
198   ssize_t nread;
199   curl_socklen_t l = sizeof(conn->local_addr);
200   CURLcode result;
201   const char *service = data->set.str[STRING_SERVICE_NAME] ?
202                         data->set.str[STRING_SERVICE_NAME] :
203                         "ftp";
204   const char *srv_host = "host";
205   gss_buffer_desc input_buffer, output_buffer, *gssresp;
206   gss_buffer_desc _gssresp = GSS_C_EMPTY_BUFFER;
207   OM_uint32 maj, min;
208   gss_name_t gssname;
209   gss_ctx_id_t *context = app_data;
210   struct gss_channel_bindings_struct chan;
211   size_t base64_sz = 0;
212   struct sockaddr_in *remote_addr =
213     (struct sockaddr_in *)(void *)&conn->remote_addr->curl_sa_addr;
214   char *stringp;
215 
216   if(getsockname(conn->sock[FIRSTSOCKET],
217                  (struct sockaddr *)&conn->local_addr, &l) < 0)
218     perror("getsockname()");
219 
220   chan.initiator_addrtype = GSS_C_AF_INET;
221   chan.initiator_address.length = l - 4;
222   chan.initiator_address.value = &conn->local_addr.sin_addr.s_addr;
223   chan.acceptor_addrtype = GSS_C_AF_INET;
224   chan.acceptor_address.length = l - 4;
225   chan.acceptor_address.value = &remote_addr->sin_addr.s_addr;
226   chan.application_data.length = 0;
227   chan.application_data.value = NULL;
228 
229   /* this loop will execute twice (once for service, once for host) */
230   for(;;) {
231     /* this really should not be repeated here, but cannot help it */
232     if(service == srv_host) {
233       result = ftpsend(data, conn, "AUTH GSSAPI");
234       if(result)
235         return -2;
236 
237       if(Curl_GetFTPResponse(data, &nread, NULL))
238         return -1;
239       else {
240         struct pingpong *pp = &conn->proto.ftpc.pp;
241         char *line = Curl_dyn_ptr(&pp->recvbuf);
242         if(line[0] != '3')
243           return -1;
244       }
245     }
246 
247     stringp = aprintf("%s@%s", service, host);
248     if(!stringp)
249       return -2;
250 
251     input_buffer.value = stringp;
252     input_buffer.length = strlen(stringp);
253     maj = gss_import_name(&min, &input_buffer, GSS_C_NT_HOSTBASED_SERVICE,
254                           &gssname);
255     free(stringp);
256     if(maj != GSS_S_COMPLETE) {
257       gss_release_name(&min, &gssname);
258       if(service == srv_host) {
259         failf(data, "Error importing service name %s@%s", service, host);
260         return AUTH_ERROR;
261       }
262       service = srv_host;
263       continue;
264     }
265     /* We pass NULL as |output_name_type| to avoid a leak. */
266     gss_display_name(&min, gssname, &output_buffer, NULL);
267     infof(data, "Trying against %s", (char *)output_buffer.value);
268     gssresp = GSS_C_NO_BUFFER;
269     *context = GSS_C_NO_CONTEXT;
270 
271     do {
272       /* Release the buffer at each iteration to avoid leaking: the first time
273          we are releasing the memory from gss_display_name. The last item is
274          taken care by a final gss_release_buffer. */
275       gss_release_buffer(&min, &output_buffer);
276       ret = AUTH_OK;
277       maj = Curl_gss_init_sec_context(data,
278                                       &min,
279                                       context,
280                                       gssname,
281                                       &Curl_krb5_mech_oid,
282                                       &chan,
283                                       gssresp,
284                                       &output_buffer,
285                                       TRUE,
286                                       NULL);
287 
288       if(gssresp) {
289         free(_gssresp.value);
290         gssresp = NULL;
291       }
292 
293       if(GSS_ERROR(maj)) {
294         infof(data, "Error creating security context");
295         ret = AUTH_ERROR;
296         break;
297       }
298 
299       if(output_buffer.length) {
300         char *cmd;
301 
302         result = Curl_base64_encode((char *)output_buffer.value,
303                                     output_buffer.length, &p, &base64_sz);
304         if(result) {
305           infof(data, "base64-encoding: %s", curl_easy_strerror(result));
306           ret = AUTH_ERROR;
307           break;
308         }
309 
310         cmd = aprintf("ADAT %s", p);
311         if(cmd)
312           result = ftpsend(data, conn, cmd);
313         else
314           result = CURLE_OUT_OF_MEMORY;
315 
316         free(p);
317         free(cmd);
318 
319         if(result) {
320           ret = -2;
321           break;
322         }
323 
324         if(Curl_GetFTPResponse(data, &nread, NULL)) {
325           ret = -1;
326           break;
327         }
328         else {
329           struct pingpong *pp = &conn->proto.ftpc.pp;
330           size_t len = Curl_dyn_len(&pp->recvbuf);
331           p = Curl_dyn_ptr(&pp->recvbuf);
332           if((len < 4) || (p[0] != '2' && p[0] != '3')) {
333             infof(data, "Server did not accept auth data");
334             ret = AUTH_ERROR;
335             break;
336           }
337         }
338 
339         _gssresp.value = NULL; /* make sure it is initialized */
340         _gssresp.length = 0;
341         p += 4; /* over '789 ' */
342         p = strstr(p, "ADAT=");
343         if(p) {
344           unsigned char *outptr;
345           size_t outlen;
346           result = Curl_base64_decode(p + 5, &outptr, &outlen);
347           if(result) {
348             failf(data, "base64-decoding: %s", curl_easy_strerror(result));
349             ret = AUTH_CONTINUE;
350             break;
351           }
352           _gssresp.value = outptr;
353           _gssresp.length = outlen;
354         }
355 
356         gssresp = &_gssresp;
357       }
358     } while(maj == GSS_S_CONTINUE_NEEDED);
359 
360     gss_release_name(&min, &gssname);
361     gss_release_buffer(&min, &output_buffer);
362 
363     if(gssresp)
364       free(_gssresp.value);
365 
366     if(ret == AUTH_OK || service == srv_host)
367       break;
368 
369     service = srv_host;
370   }
371   return ret;
372 }
373 
krb5_end(void * app_data)374 static void krb5_end(void *app_data)
375 {
376   OM_uint32 min;
377   gss_ctx_id_t *context = app_data;
378   if(*context != GSS_C_NO_CONTEXT) {
379     OM_uint32 maj = gss_delete_sec_context(&min, context, GSS_C_NO_BUFFER);
380     (void)maj;
381     DEBUGASSERT(maj == GSS_S_COMPLETE);
382   }
383 }
384 
385 static const struct Curl_sec_client_mech Curl_krb5_client_mech = {
386   "GSSAPI",
387   sizeof(gss_ctx_id_t),
388   krb5_init,
389   krb5_auth,
390   krb5_end,
391   krb5_check_prot,
392 
393   krb5_encode,
394   krb5_decode
395 };
396 
397 static const struct {
398   unsigned char level;
399   const char *name;
400 } level_names[] = {
401   { PROT_CLEAR, "clear" },
402   { PROT_SAFE, "safe" },
403   { PROT_CONFIDENTIAL, "confidential" },
404   { PROT_PRIVATE, "private" }
405 };
406 
name_to_level(const char * name)407 static unsigned char name_to_level(const char *name)
408 {
409   int i;
410   for(i = 0; i < (int)sizeof(level_names)/(int)sizeof(level_names[0]); i++)
411     if(curl_strequal(name, level_names[i].name))
412       return level_names[i].level;
413   return PROT_NONE;
414 }
415 
416 /* Convert a protocol |level| to its char representation.
417    We take an int to catch programming mistakes. */
level_to_char(int level)418 static char level_to_char(int level)
419 {
420   switch(level) {
421   case PROT_CLEAR:
422     return 'C';
423   case PROT_SAFE:
424     return 'S';
425   case PROT_CONFIDENTIAL:
426     return 'E';
427   case PROT_PRIVATE:
428     return 'P';
429   case PROT_CMD:
430   default:
431     /* Those 2 cases should not be reached! */
432     break;
433   }
434   DEBUGASSERT(0);
435   /* Default to the most secure alternative. */
436   return 'P';
437 }
438 
439 /* Send an FTP command defined by |message| and the optional arguments. The
440    function returns the ftp_code. If an error occurs, -1 is returned. */
441 static int ftp_send_command(struct Curl_easy *data, const char *message, ...)
442   CURL_PRINTF(2, 3);
443 
ftp_send_command(struct Curl_easy * data,const char * message,...)444 static int ftp_send_command(struct Curl_easy *data, const char *message, ...)
445 {
446   int ftp_code;
447   ssize_t nread = 0;
448   va_list args;
449   char print_buffer[50];
450 
451   va_start(args, message);
452   mvsnprintf(print_buffer, sizeof(print_buffer), message, args);
453   va_end(args);
454 
455   if(ftpsend(data, data->conn, print_buffer)) {
456     ftp_code = -1;
457   }
458   else {
459     if(Curl_GetFTPResponse(data, &nread, &ftp_code))
460       ftp_code = -1;
461   }
462 
463   (void)nread; /* Unused */
464   return ftp_code;
465 }
466 
467 /* Read |len| from the socket |fd| and store it in |to|. Return a CURLcode
468    saying whether an error occurred or CURLE_OK if |len| was read. */
469 static CURLcode
socket_read(struct Curl_easy * data,int sockindex,void * to,size_t len)470 socket_read(struct Curl_easy *data, int sockindex, void *to, size_t len)
471 {
472   char *to_p = to;
473   CURLcode result;
474   ssize_t nread = 0;
475 
476   while(len > 0) {
477     result = Curl_conn_recv(data, sockindex, to_p, len, &nread);
478     if(nread > 0) {
479       len -= nread;
480       to_p += nread;
481     }
482     else {
483       if(result == CURLE_AGAIN)
484         continue;
485       return result;
486     }
487   }
488   return CURLE_OK;
489 }
490 
491 
492 /* Write |len| bytes from the buffer |to| to the socket |fd|. Return a
493    CURLcode saying whether an error occurred or CURLE_OK if |len| was
494    written. */
495 static CURLcode
socket_write(struct Curl_easy * data,int sockindex,const void * to,size_t len)496 socket_write(struct Curl_easy *data, int sockindex, const void *to,
497              size_t len)
498 {
499   const char *to_p = to;
500   CURLcode result;
501   size_t written;
502 
503   while(len > 0) {
504     result = Curl_conn_send(data, sockindex, to_p, len, FALSE, &written);
505     if(!result && written > 0) {
506       len -= written;
507       to_p += written;
508     }
509     else {
510       if(result == CURLE_AGAIN)
511         continue;
512       return result;
513     }
514   }
515   return CURLE_OK;
516 }
517 
read_data(struct Curl_easy * data,int sockindex,struct krb5buffer * buf)518 static CURLcode read_data(struct Curl_easy *data, int sockindex,
519                           struct krb5buffer *buf)
520 {
521   struct connectdata *conn = data->conn;
522   int len;
523   CURLcode result;
524   int nread;
525 
526   result = socket_read(data, sockindex, &len, sizeof(len));
527   if(result)
528     return result;
529 
530   if(len) {
531     len = (int)ntohl((uint32_t)len);
532     if(len > CURL_MAX_INPUT_LENGTH)
533       return CURLE_TOO_LARGE;
534 
535     Curl_dyn_reset(&buf->buf);
536   }
537   else
538     return CURLE_RECV_ERROR;
539 
540   do {
541     char buffer[1024];
542     nread = CURLMIN(len, (int)sizeof(buffer));
543     result = socket_read(data, sockindex, buffer, (size_t)nread);
544     if(result)
545       return result;
546     result = Curl_dyn_addn(&buf->buf, buffer, nread);
547     if(result)
548       return result;
549     len -= nread;
550   } while(len);
551   /* this decodes the dynbuf *in place* */
552   nread = conn->mech->decode(conn->app_data,
553                              Curl_dyn_ptr(&buf->buf),
554                              len, conn->data_prot, conn);
555   if(nread < 0)
556     return CURLE_RECV_ERROR;
557   Curl_dyn_setlen(&buf->buf, nread);
558   buf->index = 0;
559   return CURLE_OK;
560 }
561 
562 static size_t
buffer_read(struct krb5buffer * buf,void * data,size_t len)563 buffer_read(struct krb5buffer *buf, void *data, size_t len)
564 {
565   size_t size = Curl_dyn_len(&buf->buf);
566   if(size - buf->index < len)
567     len = size - buf->index;
568   memcpy(data, Curl_dyn_ptr(&buf->buf) + buf->index, len);
569   buf->index += len;
570   return len;
571 }
572 
573 /* Matches Curl_recv signature */
sec_recv(struct Curl_easy * data,int sockindex,char * buffer,size_t len,CURLcode * err)574 static ssize_t sec_recv(struct Curl_easy *data, int sockindex,
575                         char *buffer, size_t len, CURLcode *err)
576 {
577   size_t bytes_read;
578   size_t total_read = 0;
579   struct connectdata *conn = data->conn;
580 
581   *err = CURLE_OK;
582 
583   /* Handle clear text response. */
584   if(conn->sec_complete == 0 || conn->data_prot == PROT_CLEAR) {
585     ssize_t nread;
586     *err = Curl_conn_recv(data, sockindex, buffer, len, &nread);
587     return nread;
588   }
589 
590   if(conn->in_buffer.eof_flag) {
591     conn->in_buffer.eof_flag = 0;
592     return 0;
593   }
594 
595   bytes_read = buffer_read(&conn->in_buffer, buffer, len);
596   len -= bytes_read;
597   total_read += bytes_read;
598   buffer += bytes_read;
599 
600   while(len > 0) {
601     if(read_data(data, sockindex, &conn->in_buffer))
602       return -1;
603     if(Curl_dyn_len(&conn->in_buffer.buf) == 0) {
604       if(bytes_read > 0)
605         conn->in_buffer.eof_flag = 1;
606       return bytes_read;
607     }
608     bytes_read = buffer_read(&conn->in_buffer, buffer, len);
609     len -= bytes_read;
610     total_read += bytes_read;
611     buffer += bytes_read;
612   }
613   return total_read;
614 }
615 
616 /* Send |length| bytes from |from| to the |sockindex| socket taking care of
617    encoding and negotiating with the server. |from| can be NULL. */
do_sec_send(struct Curl_easy * data,struct connectdata * conn,int sockindex,const char * from,int length)618 static void do_sec_send(struct Curl_easy *data, struct connectdata *conn,
619                         int sockindex, const char *from, int length)
620 {
621   int bytes, htonl_bytes; /* 32-bit integers for htonl */
622   char *buffer = NULL;
623   char *cmd_buffer;
624   size_t cmd_size = 0;
625   CURLcode error;
626   enum protection_level prot_level = conn->data_prot;
627   bool iscmd = (prot_level == PROT_CMD);
628 
629   DEBUGASSERT(prot_level > PROT_NONE && prot_level < PROT_LAST);
630 
631   if(iscmd) {
632     if(!strncmp(from, "PASS ", 5) || !strncmp(from, "ACCT ", 5))
633       prot_level = PROT_PRIVATE;
634     else
635       prot_level = conn->command_prot;
636   }
637   bytes = conn->mech->encode(conn->app_data, from, length, (int)prot_level,
638                              (void **)&buffer);
639   if(!buffer || bytes <= 0)
640     return; /* error */
641 
642   if(iscmd) {
643     error = Curl_base64_encode(buffer, curlx_sitouz(bytes),
644                                &cmd_buffer, &cmd_size);
645     if(error) {
646       free(buffer);
647       return; /* error */
648     }
649     if(cmd_size > 0) {
650       static const char *enc = "ENC ";
651       static const char *mic = "MIC ";
652       if(prot_level == PROT_PRIVATE)
653         socket_write(data, sockindex, enc, 4);
654       else
655         socket_write(data, sockindex, mic, 4);
656 
657       socket_write(data, sockindex, cmd_buffer, cmd_size);
658       socket_write(data, sockindex, "\r\n", 2);
659       infof(data, "Send: %s%s", prot_level == PROT_PRIVATE ? enc : mic,
660             cmd_buffer);
661       free(cmd_buffer);
662     }
663   }
664   else {
665     htonl_bytes = (int)htonl((OM_uint32)bytes);
666     socket_write(data, sockindex, &htonl_bytes, sizeof(htonl_bytes));
667     socket_write(data, sockindex, buffer, curlx_sitouz(bytes));
668   }
669   free(buffer);
670 }
671 
sec_write(struct Curl_easy * data,struct connectdata * conn,int sockindex,const char * buffer,size_t length)672 static ssize_t sec_write(struct Curl_easy *data, struct connectdata *conn,
673                          int sockindex, const char *buffer, size_t length)
674 {
675   ssize_t tx = 0, len = conn->buffer_size;
676 
677   if(len <= 0)
678     len = length;
679   while(length) {
680     if(length < (size_t)len)
681       len = length;
682 
683     do_sec_send(data, conn, sockindex, buffer, curlx_sztosi(len));
684     length -= len;
685     buffer += len;
686     tx += len;
687   }
688   return tx;
689 }
690 
691 /* Matches Curl_send signature */
sec_send(struct Curl_easy * data,int sockindex,const void * buffer,size_t len,bool eos,CURLcode * err)692 static ssize_t sec_send(struct Curl_easy *data, int sockindex,
693                         const void *buffer, size_t len, bool eos,
694                         CURLcode *err)
695 {
696   struct connectdata *conn = data->conn;
697   (void)eos; /* unused */
698   *err = CURLE_OK;
699   return sec_write(data, conn, sockindex, buffer, len);
700 }
701 
Curl_sec_read_msg(struct Curl_easy * data,struct connectdata * conn,char * buffer,enum protection_level level)702 int Curl_sec_read_msg(struct Curl_easy *data, struct connectdata *conn,
703                       char *buffer, enum protection_level level)
704 {
705   /* decoded_len should be size_t or ssize_t but conn->mech->decode returns an
706      int */
707   int decoded_len;
708   char *buf;
709   int ret_code = 0;
710   size_t decoded_sz = 0;
711   CURLcode error;
712 
713   (void) data;
714 
715   if(!conn->mech)
716     /* not initialized, return error */
717     return -1;
718 
719   DEBUGASSERT(level > PROT_NONE && level < PROT_LAST);
720 
721   error = Curl_base64_decode(buffer + 4, (unsigned char **)&buf, &decoded_sz);
722   if(error || decoded_sz == 0)
723     return -1;
724 
725   if(decoded_sz > (size_t)INT_MAX) {
726     free(buf);
727     return -1;
728   }
729   decoded_len = curlx_uztosi(decoded_sz);
730 
731   decoded_len = conn->mech->decode(conn->app_data, buf, decoded_len,
732                                    (int)level, conn);
733   if(decoded_len <= 0) {
734     free(buf);
735     return -1;
736   }
737 
738   {
739     buf[decoded_len] = '\n';
740     Curl_debug(data, CURLINFO_HEADER_IN, buf, decoded_len + 1);
741   }
742 
743   buf[decoded_len] = '\0';
744   if(decoded_len <= 3)
745     /* suspiciously short */
746     return 0;
747 
748   if(buf[3] != '-')
749     ret_code = atoi(buf);
750 
751   if(buf[decoded_len - 1] == '\n')
752     buf[decoded_len - 1] = '\0';
753   strcpy(buffer, buf);
754   free(buf);
755   return ret_code;
756 }
757 
sec_set_protection_level(struct Curl_easy * data)758 static int sec_set_protection_level(struct Curl_easy *data)
759 {
760   int code;
761   struct connectdata *conn = data->conn;
762   unsigned char level = conn->request_data_prot;
763 
764   DEBUGASSERT(level > PROT_NONE && level < PROT_LAST);
765 
766   if(!conn->sec_complete) {
767     infof(data, "Trying to change the protection level after the"
768                 " completion of the data exchange.");
769     return -1;
770   }
771 
772   /* Bail out if we try to set up the same level */
773   if(conn->data_prot == level)
774     return 0;
775 
776   if(level) {
777     char *pbsz;
778     unsigned int buffer_size = 1 << 20; /* 1048576 */
779     struct pingpong *pp = &conn->proto.ftpc.pp;
780     char *line;
781 
782     code = ftp_send_command(data, "PBSZ %u", buffer_size);
783     if(code < 0)
784       return -1;
785 
786     if(code/100 != 2) {
787       failf(data, "Failed to set the protection's buffer size.");
788       return -1;
789     }
790     conn->buffer_size = buffer_size;
791 
792     line = Curl_dyn_ptr(&pp->recvbuf);
793     pbsz = strstr(line, "PBSZ=");
794     if(pbsz) {
795       /* stick to default value if the check fails */
796       if(ISDIGIT(pbsz[5]))
797         buffer_size = (unsigned int)atoi(&pbsz[5]);
798       if(buffer_size < conn->buffer_size)
799         conn->buffer_size = buffer_size;
800     }
801   }
802 
803   /* Now try to negotiate the protection level. */
804   code = ftp_send_command(data, "PROT %c", level_to_char(level));
805 
806   if(code < 0)
807     return -1;
808 
809   if(code/100 != 2) {
810     failf(data, "Failed to set the protection level.");
811     return -1;
812   }
813 
814   conn->data_prot = level;
815   if(level == PROT_PRIVATE)
816     conn->command_prot = level;
817 
818   return 0;
819 }
820 
821 int
Curl_sec_request_prot(struct connectdata * conn,const char * level)822 Curl_sec_request_prot(struct connectdata *conn, const char *level)
823 {
824   unsigned char l = name_to_level(level);
825   if(l == PROT_NONE)
826     return -1;
827   DEBUGASSERT(l > PROT_NONE && l < PROT_LAST);
828   conn->request_data_prot = l;
829   return 0;
830 }
831 
choose_mech(struct Curl_easy * data,struct connectdata * conn)832 static CURLcode choose_mech(struct Curl_easy *data, struct connectdata *conn)
833 {
834   int ret;
835   void *tmp_allocation;
836   const struct Curl_sec_client_mech *mech = &Curl_krb5_client_mech;
837 
838   tmp_allocation = realloc(conn->app_data, mech->size);
839   if(!tmp_allocation) {
840     failf(data, "Failed realloc of size %zu", mech->size);
841     mech = NULL;
842     return CURLE_OUT_OF_MEMORY;
843   }
844   conn->app_data = tmp_allocation;
845 
846   if(mech->init) {
847     ret = mech->init(conn->app_data);
848     if(ret) {
849       infof(data, "Failed initialization for %s. Skipping it.",
850             mech->name);
851       return CURLE_FAILED_INIT;
852     }
853     Curl_dyn_init(&conn->in_buffer.buf, CURL_MAX_INPUT_LENGTH);
854   }
855 
856   infof(data, "Trying mechanism %s...", mech->name);
857   ret = ftp_send_command(data, "AUTH %s", mech->name);
858   if(ret < 0)
859     return CURLE_COULDNT_CONNECT;
860 
861   if(ret/100 != 3) {
862     switch(ret) {
863     case 504:
864       infof(data, "Mechanism %s is not supported by the server (server "
865             "returned ftp code: 504).", mech->name);
866       break;
867     case 534:
868       infof(data, "Mechanism %s was rejected by the server (server returned "
869             "ftp code: 534).", mech->name);
870       break;
871     default:
872       if(ret/100 == 5) {
873         infof(data, "server does not support the security extensions");
874         return CURLE_USE_SSL_FAILED;
875       }
876       break;
877     }
878     return CURLE_LOGIN_DENIED;
879   }
880 
881   /* Authenticate */
882   ret = mech->auth(conn->app_data, data, conn);
883 
884   if(ret != AUTH_CONTINUE) {
885     if(ret != AUTH_OK) {
886       /* Mechanism has dumped the error to stderr, do not error here. */
887       return CURLE_USE_SSL_FAILED;
888     }
889     DEBUGASSERT(ret == AUTH_OK);
890 
891     conn->mech = mech;
892     conn->sec_complete = 1;
893     conn->recv[FIRSTSOCKET] = sec_recv;
894     conn->send[FIRSTSOCKET] = sec_send;
895     conn->recv[SECONDARYSOCKET] = sec_recv;
896     conn->send[SECONDARYSOCKET] = sec_send;
897     conn->command_prot = PROT_SAFE;
898     /* Set the requested protection level */
899     /* BLOCKING */
900     (void)sec_set_protection_level(data);
901   }
902 
903   return CURLE_OK;
904 }
905 
906 CURLcode
Curl_sec_login(struct Curl_easy * data,struct connectdata * conn)907 Curl_sec_login(struct Curl_easy *data, struct connectdata *conn)
908 {
909   return choose_mech(data, conn);
910 }
911 
912 
913 void
Curl_sec_end(struct connectdata * conn)914 Curl_sec_end(struct connectdata *conn)
915 {
916   if(conn->mech && conn->mech->end)
917     conn->mech->end(conn->app_data);
918   Curl_safefree(conn->app_data);
919   Curl_dyn_free(&conn->in_buffer.buf);
920   conn->in_buffer.index = 0;
921   conn->in_buffer.eof_flag = 0;
922   conn->sec_complete = 0;
923   conn->data_prot = PROT_CLEAR;
924   conn->mech = NULL;
925 }
926 
927 #endif /* HAVE_GSSAPI && !CURL_DISABLE_FTP */
928