File: loginjob.cpp

package info (click to toggle)
kdepimlibs 4:4.14.10-11
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 35,856 kB
  • sloc: cpp: 269,391; xml: 4,188; ansic: 2,946; yacc: 1,904; perl: 381; ruby: 60; sh: 60; makefile: 13
file content (628 lines) | stat: -rw-r--r-- 18,954 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
/*
    Copyright (c) 2009 Kevin Ottens <ervin@kde.org>
    Copyright (c) 2009 Andras Mantia <amantia@kde.org>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This library is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "loginjob.h"

#include <KDE/KLocalizedString>
#include <KDE/KDebug>
#include <ktcpsocket.h>

#include "job_p.h"
#include "message_p.h"
#include "session_p.h"
#include "rfccodecs.h"

#include "common.h"

extern "C" {
#include <sasl/sasl.h>
}

static sasl_callback_t callbacks[] = {
    { SASL_CB_ECHOPROMPT, NULL, NULL },
    { SASL_CB_NOECHOPROMPT, NULL, NULL },
    { SASL_CB_GETREALM, NULL, NULL },
    { SASL_CB_USER, NULL, NULL },
    { SASL_CB_AUTHNAME, NULL, NULL },
    { SASL_CB_PASS, NULL, NULL },
    { SASL_CB_CANON_USER, NULL, NULL },
    { SASL_CB_LIST_END, NULL, NULL }
};

namespace KIMAP
{
  class LoginJobPrivate : public JobPrivate
  {
    public:
     enum AuthState {
        StartTls = 0,
        Capability,
        Login,
        Authenticate
      };

      LoginJobPrivate( LoginJob *job, Session *session, const QString& name ) : JobPrivate( session, name ), q( job ), encryptionMode( LoginJob::Unencrypted ), authState( Login ), plainLoginDisabled( false ) {
        conn = 0;
        client_interact = 0;
      }
      ~LoginJobPrivate() { }
      bool sasl_interact();

      bool startAuthentication();
      bool answerChallenge(const QByteArray &data);
      void sslResponse(bool response);
      void saveServerGreeting(const Message &response);

      LoginJob *q;

      QString userName;
      QString authorizationName;
      QString password;
      QString serverGreeting;

      LoginJob::EncryptionMode encryptionMode;
      QString authMode;
      AuthState authState;
      QStringList capabilities;
      bool plainLoginDisabled;

      sasl_conn_t *conn;
      sasl_interact_t *client_interact;
  };
}

using namespace KIMAP;

bool LoginJobPrivate::sasl_interact()
{
  kDebug() << "sasl_interact";
  sasl_interact_t *interact = client_interact;

  //some mechanisms do not require username && pass, so it doesn't need a popup
  //window for getting this info
  for ( ; interact->id != SASL_CB_LIST_END; interact++ ) {
    if ( interact->id == SASL_CB_AUTHNAME ||
         interact->id == SASL_CB_PASS ) {
      //TODO: dialog for use name??
      break;
    }
  }

  interact = client_interact;
  while ( interact->id != SASL_CB_LIST_END ) {
    kDebug() << "SASL_INTERACT id:" << interact->id;
    switch ( interact->id ) {
      case SASL_CB_AUTHNAME:
        if ( !authorizationName.isEmpty() ) {
          kDebug() << "SASL_CB_[AUTHNAME]: '" << authorizationName << "'";
          interact->result = strdup( authorizationName.toUtf8() );
          interact->len = strlen( (const char *) interact->result );
          break;
        }
      case SASL_CB_USER:
        kDebug() << "SASL_CB_[USER|AUTHNAME]: '" << userName << "'";
        interact->result = strdup( userName.toUtf8() );
        interact->len = strlen( (const char *) interact->result );
        break;
      case SASL_CB_PASS:
        kDebug() << "SASL_CB_PASS: [hidden]";
        interact->result = strdup( password.toUtf8() );
        interact->len = strlen( (const char *) interact->result );
        break;
      default:
        interact->result = 0;
        interact->len = 0;
        break;
    }
    interact++;
  }
  return true;
}

LoginJob::LoginJob( Session *session )
  : Job( *new LoginJobPrivate( this, session, i18n( "Login" ) ) )
{
  Q_D( LoginJob );
  connect( d->sessionInternal(), SIGNAL(encryptionNegotiationResult(bool)), this, SLOT(sslResponse(bool)) );
  kDebug() << this;
}

LoginJob::~LoginJob()
{
  kDebug() << this;
}

QString LoginJob::userName() const
{
  Q_D( const LoginJob );
  return d->userName;
}

void LoginJob::setUserName( const QString &userName )
{
  Q_D( LoginJob );
  d->userName = userName;
}

QString LoginJob::authorizationName() const
{
  Q_D( const LoginJob );
  return d->authorizationName;
}

void LoginJob::setAuthorizationName( const QString& authorizationName )
{
  Q_D( LoginJob );
  d->authorizationName = authorizationName;
}

QString LoginJob::password() const
{
  Q_D( const LoginJob );
  return d->password;
}

void LoginJob::setPassword( const QString &password )
{
  Q_D( LoginJob );
  d->password = password;
}

void LoginJob::doStart()
{
  Q_D( LoginJob );

  kDebug() << this;
  // Don't authenticate on a session in the authenticated state
  if ( session()->state() == Session::Authenticated || session()->state() == Session::Selected ) {
    setError( UserDefinedError );
    setErrorText( i18n( "IMAP session in the wrong state for authentication" ) );
    emitResult();
    return;
  }

  // Trigger encryption negotiation only if needed
  EncryptionMode encryptionMode = d->encryptionMode;

  switch ( d->sessionInternal()->negotiatedEncryption() ) {
  case KTcpSocket::UnknownSslVersion:
    break; // Do nothing the encryption mode still needs to be negotiated

  // For the other cases, pretend we're going unencrypted as that's the
  // encryption mode already set on the session
  // (so for instance we won't issue another STARTTLS for nothing if that's
  // not needed)
  case KTcpSocket::SslV2:
    if ( encryptionMode == SslV2 ) {
      encryptionMode = Unencrypted;
    }
    break;
  case KTcpSocket::SslV3:
    if ( encryptionMode == SslV3 ) {
      encryptionMode = Unencrypted;
    }
    break;
  case KTcpSocket::TlsV1:
    if ( encryptionMode == TlsV1 ) {
      encryptionMode = Unencrypted;
    }
    break;
  case KTcpSocket::AnySslVersion:
    if ( encryptionMode == AnySslVersion ) {
      encryptionMode = Unencrypted;
    }
    break;
  }

  if ( encryptionMode == SslV2 ||
       encryptionMode == SslV3 ||
       encryptionMode == SslV3_1 ||
       encryptionMode == AnySslVersion ) {
    KTcpSocket::SslVersion version = KTcpSocket::SslV2;
    if ( encryptionMode == SslV3 ) {
      version = KTcpSocket::SslV3;
    }
    if ( encryptionMode == SslV3_1 ) {
      version = KTcpSocket::SslV3_1;
    }
    if ( encryptionMode == AnySslVersion ) {
      version = KTcpSocket::AnySslVersion;
    }
    d->sessionInternal()->startSsl( version );

  } else if ( encryptionMode == TlsV1 ) {
    d->authState = LoginJobPrivate::StartTls;
    d->tags << d->sessionInternal()->sendCommand( "STARTTLS" );

  } else  if ( encryptionMode == Unencrypted  ) {
    if ( d->authMode.isEmpty() ) {
      d->authState = LoginJobPrivate::Login;
      kDebug() << "sending LOGIN";
      d->tags << d->sessionInternal()->sendCommand( "LOGIN",
                                                    '"' + quoteIMAP( d->userName ).toUtf8() + '"' +
                                                    ' ' +
                                                    '"' + quoteIMAP( d->password  ).toUtf8() + '"' );
    } else {
      if ( !d->startAuthentication() ) {
        emitResult();
      }
    }
  }
}

void LoginJob::handleResponse( const Message &response )
{
  Q_D( LoginJob );

  if ( response.content.isEmpty() ) {
    return;
  }

  //set the actual command name for standard responses
  QString commandName = i18n( "Login" );
  if ( d->authState == LoginJobPrivate::Capability ) {
    commandName = i18n( "Capability" );
  } else if ( d->authState == LoginJobPrivate::StartTls ) {
    commandName = i18n( "StartTls" );
  }

  enum ResponseCode {
    OK,
    ERR,
    UNTAGGED,
    CONTINUATION,
    MALFORMED
  };

  QByteArray tag = response.content.first().toString();
  ResponseCode code = OK;

  kDebug() << commandName << tag;

  if ( tag == "+" ) {
    code = CONTINUATION;
  } else if ( tag == "*" ) {
    if ( response.content.size() < 2 ) {
      code = MALFORMED; // Received empty untagged response
    } else {
      code = UNTAGGED;
    }
  } else if ( d->tags.contains( tag ) ) {
    if ( response.content.size() < 2 ) {
      code = MALFORMED;
    } else if ( response.content[1].toString() == "OK" ) {
      code = OK;
    } else {
      code = ERR;
    }
  }

  switch ( code ) {
    case MALFORMED:
      // We'll handle it later
      break;

    case ERR:
      //server replied with NO or BAD for SASL authentication
      if ( d->authState == LoginJobPrivate::Authenticate ) {
        sasl_dispose( &d->conn );
      }

      setError( UserDefinedError );
      setErrorText( i18n( "%1 failed, server replied: %2", commandName, QLatin1String(response.toString().constData()) ) );
      emitResult();
      return;

    case UNTAGGED:
      // The only untagged response interesting for us here is CAPABILITY
      if ( response.content[1].toString() == "CAPABILITY" ) {
        QList<Message::Part>::const_iterator p = response.content.begin() + 2;
        while ( p != response.content.end() ) {
          QString capability = QLatin1String(p->toString());
          d->capabilities << capability;
          if ( capability == QLatin1String("LOGINDISABLED") ) {
            d->plainLoginDisabled = true;
          }
          ++p;
        }
        kDebug() << "Capabilities updated: " << d->capabilities;
      }
      break;

    case CONTINUATION:
      if ( d->authState != LoginJobPrivate::Authenticate ) {
        // Received unexpected continuation response for something
        // other than AUTHENTICATE command
        code = MALFORMED;
        break;
      }

      if ( d->authMode == QLatin1String( "PLAIN" ) ) {
        if ( response.content.size()>1 && response.content.at( 1 ).toString() == "OK" ) {
          return;
        }
        QByteArray challengeResponse;
        if ( !d->authorizationName.isEmpty() ) {
          challengeResponse+= d->authorizationName.toUtf8();
        }
        challengeResponse+= '\0';
        challengeResponse+= d->userName.toUtf8();
        challengeResponse+= '\0';
        challengeResponse+= d->password.toUtf8();
        challengeResponse = challengeResponse.toBase64();
        d->sessionInternal()->sendData( challengeResponse );
      } else if ( response.content.size() >= 2 ) {
        if ( !d->answerChallenge( QByteArray::fromBase64( response.content[1].toString() ) ) ) {
          emitResult(); //error, we're done
        }
      } else {
        // Received empty continuation for authMode other than PLAIN
        code = MALFORMED;
      }
      break;

    case OK:

      switch ( d->authState ) {
        case LoginJobPrivate::StartTls:
          d->sessionInternal()->startSsl( KTcpSocket::TlsV1 );
          break;

        case LoginJobPrivate::Capability:
          //cleartext login, if enabled
          if ( d->authMode.isEmpty() ) {
            if ( d->plainLoginDisabled ) {
              setError( UserDefinedError );
              setErrorText( i18n( "Login failed, plain login is disabled by the server." ) );
              emitResult();
            } else {
              d->authState = LoginJobPrivate::Login;
              d->tags << d->sessionInternal()->sendCommand( "LOGIN",
                                                            '"' + quoteIMAP( d->userName ).toUtf8() + '"' +
                                                            ' ' +
                                                            '"' + quoteIMAP( d->password ).toUtf8() + '"' );
            }
          } else {
            bool authModeSupported = false;
            //find the selected SASL authentication method
            Q_FOREACH ( const QString &capability, d->capabilities ) {
              if ( capability.startsWith( QLatin1String( "AUTH=" ) ) ) {
                if ( capability.mid( 5 ) == d->authMode ) {
                  authModeSupported = true;
                  break;
                }
              }
            }
            if ( !authModeSupported ) {
              setError( UserDefinedError );
              setErrorText( i18n( "Login failed, authentication mode %1 is not supported by the server.", d->authMode ) );
              emitResult();
            } else if ( !d->startAuthentication() ) {
              emitResult(); //problem, we're done
            }
          }
          break;

        case LoginJobPrivate::Authenticate:
          sasl_dispose( &d->conn ); //SASL authentication done
          // Fall through
        case LoginJobPrivate::Login:
          d->saveServerGreeting( response );
          emitResult(); //got an OK, command done
          break;

      }

  }

  if ( code == MALFORMED ) {
    setErrorText( i18n( "%1 failed, malformed reply from the server.", commandName ) );
    emitResult();
  }
}

bool LoginJobPrivate::startAuthentication()
{
  //SASL authentication
  if ( !initSASL() ) {
    q->setError( LoginJob::UserDefinedError );
    q->setErrorText( i18n( "Login failed, client cannot initialize the SASL library." ) );
    return false;
  }

  authState = LoginJobPrivate::Authenticate;
  const char *out = 0;
  uint outlen = 0;
  const char *mechusing = 0;

  int result = sasl_client_new( "imap", m_session->hostName().toLatin1(), 0, 0, callbacks, 0, &conn );
  if ( result != SASL_OK ) {
    kDebug() << "sasl_client_new failed with:" << result;
    q->setError( LoginJob::UserDefinedError );
    q->setErrorText( QString::fromUtf8( sasl_errdetail( conn ) ) );
    return false;
  }

  do {
    result = sasl_client_start( conn, authMode.toLatin1(), &client_interact, capabilities.contains( QLatin1String("SASL-IR") ) ? &out : 0, &outlen, &mechusing );

    if ( result == SASL_INTERACT ) {
      if ( !sasl_interact() ) {
        sasl_dispose( &conn );
        q->setError( LoginJob::UserDefinedError ); //TODO: check up the actual error
        return false;
      }
    }
  } while ( result == SASL_INTERACT );

  if ( result != SASL_CONTINUE && result != SASL_OK ) {
    kDebug() << "sasl_client_start failed with:" << result;
    q->setError( LoginJob::UserDefinedError );
    q->setErrorText( QString::fromUtf8( sasl_errdetail( conn ) ) );
    sasl_dispose( &conn );
    return false;
  }

  QByteArray tmp = QByteArray::fromRawData( out, outlen );
  QByteArray challenge = tmp.toBase64();

  if ( challenge.isEmpty() ) {
    tags << sessionInternal()->sendCommand( "AUTHENTICATE", authMode.toLatin1() );
  } else {
    tags << sessionInternal()->sendCommand( "AUTHENTICATE", authMode.toLatin1() + ' ' + challenge );
  }

  return true;
}

bool LoginJobPrivate::answerChallenge(const QByteArray &data)
{
  QByteArray challenge = data;
  int result = -1;
  const char *out = 0;
  uint outlen = 0;
  do {
    result = sasl_client_step( conn, challenge.isEmpty() ? 0 : challenge.data(),
                               challenge.size(),
                               &client_interact,
                               &out, &outlen );

    if ( result == SASL_INTERACT ) {
      if ( !sasl_interact() ) {
        q->setError( LoginJob::UserDefinedError ); //TODO: check up the actual error
        sasl_dispose( &conn );
        return false;
      }
    }
  } while ( result == SASL_INTERACT );

  if ( result != SASL_CONTINUE && result != SASL_OK ) {
    kDebug() << "sasl_client_step failed with:" << result;
    q->setError( LoginJob::UserDefinedError ); //TODO: check up the actual error
    q->setErrorText( QString::fromUtf8( sasl_errdetail( conn ) ) );
    sasl_dispose( &conn );
    return false;
  }

  QByteArray tmp = QByteArray::fromRawData( out, outlen );
  challenge = tmp.toBase64();

  sessionInternal()->sendData( challenge );

  return true;
}

void LoginJobPrivate::sslResponse(bool response)
{
  if ( response ) {
    authState = LoginJobPrivate::Capability;
    tags << sessionInternal()->sendCommand( "CAPABILITY" );
  } else {
    q->setError( LoginJob::ERR_SSL_FAILED );
    q->setErrorText( i18n( "Login failed, TLS negotiation failed." ) );
    encryptionMode = LoginJob::Unencrypted;
    q->emitResult();
  }
}

void LoginJob::setEncryptionMode(EncryptionMode mode)
{
  Q_D( LoginJob );
  d->encryptionMode = mode;
}

LoginJob::EncryptionMode LoginJob::encryptionMode()
{
  Q_D( LoginJob );
  return d->encryptionMode;
}

void LoginJob::setAuthenticationMode(AuthenticationMode mode)
{
  Q_D( LoginJob );
  switch ( mode ) {
    case ClearText: d->authMode = QLatin1String( "");
      break;
    case Login: d->authMode = QLatin1String("LOGIN");
      break;
    case Plain: d->authMode = QLatin1String("PLAIN");
      break;
    case CramMD5: d->authMode = QLatin1String("CRAM-MD5");
      break;
    case DigestMD5: d->authMode = QLatin1String("DIGEST-MD5");
      break;
    case GSSAPI: d->authMode = QLatin1String("GSSAPI");
      break;
    case Anonymous: d->authMode = QLatin1String("ANONYMOUS");
      break;
    case XOAuth2: d->authMode = QLatin1String("XOAUTH2");
      break;
    default:
      d->authMode = QLatin1String("");
  }
}

void LoginJob::connectionLost()
{
  Q_D( LoginJob );

  //don't emit the result if the connection was lost before getting the tls result, as it can mean
  //the TLS handshake failed and the socket was reconnected in normal mode
  if ( d->authState != LoginJobPrivate::StartTls ) {
    kWarning() << "Connection to server lost " << d->m_socketError;
    if ( d->m_socketError == KTcpSocket::SslHandshakeFailedError) {
      setError( KJob::UserDefinedError );
      setErrorText( i18n( "SSL handshake failed." ) );
      emitResult();
    } else {
      setError( ERR_COULD_NOT_CONNECT );
      setErrorText( i18n( "Connection to server lost." ) );
      emitResult();
    }
  }
}

void LoginJobPrivate::saveServerGreeting(const Message &response)
{
  // Concatenate the parts of the server response into a string, while dropping the first two parts
  // (the response tag and the "OK" code), and being careful not to add useless extra whitespace.

  for ( int i = 2; i < response.content.size(); i++ ) {
    if ( response.content.at( i ).type() == Message::Part::List ) {
      serverGreeting += QLatin1Char('(');
      foreach ( const QByteArray &item, response.content.at( i ).toList() ) {
        serverGreeting += QLatin1String(item) + QLatin1Char(' ');
      }
      serverGreeting.chop( 1 );
      serverGreeting += QLatin1String(") ");
    } else {
      serverGreeting+= QLatin1String(response.content.at( i ).toString()) + QLatin1Char(' ');
    }
  }
  serverGreeting.chop( 1 );
}

QString LoginJob::serverGreeting() const
{
  Q_D( const LoginJob );
  return d->serverGreeting;
}

#include "moc_loginjob.cpp"