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