-
Notifications
You must be signed in to change notification settings - Fork 143
/
helper.cpp
774 lines (661 loc) · 17 KB
/
helper.cpp
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2016 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "helper.h"
#include "../../stringtools.h"
#include "../database.h"
#include <stdlib.h>
#include <algorithm>
#include "../server_settings.h"
#include "../../urlplugin/IUrlFactory.h"
#include "../../urbackupcommon/glob.h"
#include "../../cryptoplugin/ICryptoFactory.h"
#include "../../Interface/Thread.h"
extern std::string server_identity;
extern IUrlFactory *url_fak;
extern ICryptoFactory *crypto_fak;
ISharedMutex* Helper::rate_limit_mutex;
Helper::rate_limit_map Helper::rates_per_bucket;
std::map<std::string, int64> Helper::banned_ips;
ICondition* Helper::login_wait_cond;
IMutex* Helper::login_wait_mutex;
std::set<std::string> Helper::logging_in;
Helper::Helper(THREAD_ID pTID, str_map *pPOST, str_map *pPARAMS)
{
prioritized = os_enable_prioritize(prio_info, Prio_SlightPrioritize);
session=NULL;
update(pTID,pPOST,pPARAMS);
Server->addHeader(pTID, "X-Frame-Options: DENY");
}
void Helper::update(THREAD_ID pTID, str_map *pPOST, str_map *pPARAMS)
{
tid=pTID;
POST=pPOST;
PARAMS=pPARAMS;
if(POST==NULL)
{
return;
}
if( session==NULL )
{
session=Server->getSessionMgr()->getUser( (*POST)["ses"], getIdentData() );
if(session!=NULL)
{
str_map::iterator it = session->mStr.find("ldap_rights");
if(it!=session->mStr.end())
{
ldap_rights = parseRightsString(it->second);
}
}
}
//Get language from ACCEPT_LANGUAGE
str_map::iterator lit=POST->find("lang");
if(lit!=POST->end() && lit->second!="-")
{
language=lit->second;
}
else
{
std::string langs=(*POST)["langs"];
std::vector<std::string> clangs;
Tokenize(langs, clangs, ",");
for(size_t j=0;j<clangs.size();++j)
{
clangs[j]=strlower(clangs[j]);
}
str_map::iterator al=PARAMS->find("ACCEPT_LANGUAGE");
if(al==PARAMS->end())
al=PARAMS->find("HTTP_ACCEPT_LANGUAGE");
if(al!=PARAMS->end())
{
std::vector<std::string> toks;
Tokenize(al->second, toks, ",");
for(size_t i=0;i<toks.size();++i)
{
std::string lstr=getuntil(";", toks[i]);
if(lstr.empty())
lstr=toks[i];
std::string prefix=getuntil("-", lstr);
if(prefix.empty())
prefix=lstr;
std::string sub=getafter("-", lstr);
if(language.empty())
{
if(std::find(clangs.begin(), clangs.end(), strlower(prefix+"_"+sub))!=clangs.end())
{
language=strlower(prefix+"_"+sub);
break;
}
if(std::find(clangs.begin(), clangs.end(), strlower(prefix))!=clangs.end())
{
language=strlower(prefix);
break;
}
}
}
if(language.empty())
{
language="en";
}
}
else
{
language="en";
}
}
if( session==NULL)
invalid_session=true;
else
invalid_session=false;
}
SUser *Helper::getSession(void)
{
return session;
}
void Helper::OverwriteLanguage( std::string pLanguage)
{
language=pLanguage;
}
ITemplate *Helper::createTemplate(std::string name)
{
IDatabase* db=NULL;//Server->getDatabase(tid, TRANSLATIONDB);
ITemplate *tmpl=Server->createTemplate("urbackup/templates/"+name);
/*if( db!=NULL )
{
tmpl->addValueTable(db, "translation_"+language );
}*/
if( invalid_session==true )
tmpl->setValue("INVALID_SESSION","true");
else if(session!=NULL)
tmpl->setValue("SESSION", session->session);
if( session!=NULL && session->id==SESSION_ID_INVALID )
tmpl->setValue("INVALID_ID","true");
templates.push_back( tmpl );
return tmpl;
}
Helper::~Helper(void)
{
if( session!=NULL )
Server->getSessionMgr()->releaseUser(session);
for(size_t i=0;i<templates.size();++i)
{
Server->destroy( templates[i] );
}
if (prioritized)
{
os_disable_prioritize(prio_info);
}
}
void Helper::Write(std::string str, bool content_type_json)
{
if (content_type_json)
{
Server->setContentType(tid, "application/json");
}
Server->Write( tid, str );
}
void Helper::WriteTemplate(ITemplate *tmpl)
{
Server->Write( tid, tmpl->getData() );
}
IDatabase *Helper::getDatabase(void)
{
return Server->getDatabase(tid, URBACKUPDB_SERVER);
}
std::string Helper::generateSession(std::string username)
{
return Server->getSessionMgr()->GenerateSessionIDWithUser( username, getIdentData());
}
std::string Helper::getRights(const std::string &domain)
{
if(session==NULL) return "none";
if(session->id==SESSION_ID_ADMIN) return "all";
if(session->id==SESSION_ID_TOKEN_AUTH && ldap_rights.empty()) return "none";
if(getRightsInt("all")=="all")
return "all";
return getRightsInt(domain);
}
namespace
{
class RateLimitTimeout : public IThread
{
public:
void operator()() {
Helper::rateLimitTimeout();
delete this;
}
};
}
void Helper::init_mutex()
{
rate_limit_mutex = Server->createSharedMutex();
login_wait_cond = Server->createCondition();
login_wait_mutex = Server->createMutex();
if (failedLoginRateLimit())
Server->createThread(new RateLimitTimeout, "rate limit timeout");
}
bool Helper::allowUserEnumeration()
{
static bool allow_user_enumeration = Server->getServerParameter("allow_user_enumeration") != "0";
return allow_user_enumeration;
}
bool Helper::failedLoginRateLimit()
{
static bool limit = Server->getServerParameter("failed_login_ratelimit") != "0";
return limit;
}
std::string Helper::getIdentData()
{
static bool lock_session = Server->getServerParameter("lock_session_to_ip_and_user_agent") == "1";
if (!lock_session)
return std::string();
std::string user_agent = (*PARAMS)["HTTP_USER_AGENT"];
return remoteAddr() + user_agent;
}
std::string Helper::getRightsInt(const std::string &domain)
{
if(session==NULL) return "none";
std::map<std::string, std::string>::iterator it=ldap_rights.find(domain);
if(it!=ldap_rights.end())
{
return it->second;
}
IQuery *q=getDatabase()->Prepare("SELECT t_right FROM settings_db.si_permissions WHERE clientid=? AND t_domain=?");
q->Bind(session->id);
q->Bind(domain);
db_results res=q->Read();
q->Reset();
if(!res.empty())
{
return res[0]["t_right"];
}
else
{
return "none";
}
}
void Helper::releaseAll(void)
{
if(session!=NULL)
{
Server->getSessionMgr()->releaseUser(session);
session=NULL;
}
}
std::string Helper::getTimeFormatString(void)
{
return "%s";
}
std::string Helper::getLanguage(void)
{
return language;
}
std::vector<int> Helper::getRightIDs(std::string rights)
{
std::vector<int> clientid;
if(rights!="all" && rights!="none" )
{
std::vector<std::string> s_clientid;
Tokenize(rights, s_clientid, ",");
for(size_t i=0;i<s_clientid.size();++i)
{
clientid.push_back(atoi(s_clientid[i].c_str()));
}
}
return clientid;
}
bool Helper::hasRights(int clientid, std::string rights, std::vector<int> right_ids)
{
bool r_ok=false;
if(rights!="all")
{
for(size_t i=0;i<right_ids.size();++i)
{
if(right_ids[i]==clientid)
{
r_ok=true;
break;
}
}
}
else
{
r_ok=true;
}
return r_ok;
}
bool Helper::checkPassword(const std::string &username, const std::string &password, int *user_id, bool plainpw)
{
IDatabase *db=getDatabase();
IQuery *q=db->Prepare("SELECT id, name, password_md5, salt, pbkdf2_rounds FROM settings_db.si_users WHERE name=?");
q->Bind(username);
db_results res=q->Read();
if(!res.empty())
{
std::string password_md5=res[0]["password_md5"];
if(!plainpw)
{
std::string r_password=Server->GenerateHexMD5((session->mStr["rnd"]+password_md5));
if(r_password!=password)
{
return false;
}
else
{
if(user_id!=NULL)
{
*user_id=watoi(res[0]["id"]);
}
return true;
}
}
else
{
std::string db_password = Server->GenerateHexMD5((res[0]["salt"]+password));
size_t pbkdf2_rounds = watoi(res[0]["pbkdf2_rounds"]);
if(pbkdf2_rounds>0)
{
db_password = strlower(crypto_fak->generatePasswordHash(hexToBytes(db_password),
(res[0]["salt"]), pbkdf2_rounds));
}
if(db_password!=password_md5)
{
return false;
}
else
{
if(user_id!=NULL)
{
*user_id=watoi(res[0]["id"]);
}
return true;
}
}
}
return false;
}
std::vector<int> Helper::clientRights(const std::string& right_name, bool& all_client_rights)
{
std::string rights=getRights(right_name);
std::vector<int> clientid;
if(rights!="all" && rights!="none" )
{
std::vector<std::string> s_clientid;
Tokenize(rights, s_clientid, ",");
for(size_t i=0;i<s_clientid.size();++i)
{
clientid.push_back(atoi(s_clientid[i].c_str()));
}
}
if(rights=="all")
{
all_client_rights=true;
}
else
{
all_client_rights=false;
}
return clientid;
}
std::string Helper::getStrippedServerIdentity(void)
{
std::string ret=server_identity;
if(ret.size()>3)
{
if(next(ret, 0, "#I"))
{
ret=ret.substr(2);
}
if(ret[ret.size()-1]=='#')
{
ret=ret.substr(0, ret.size()-1);
}
}
return ret;
}
void Helper::sleep(unsigned int ms)
{
if(session!=NULL)
{
Server->getSessionMgr()->unlockUser(session);
}
Server->wait(ms);
if(session!=NULL)
{
Server->getSessionMgr()->lockUser(session);
}
}
bool Helper::ldapEnabled()
{
IDatabase *db=getDatabase();
IQuery *q=db->Prepare("SELECT value FROM settings_db.settings WHERE clientid=0 AND key='ldap_login_enabled'");
if(q!=NULL)
{
db_results res = q->Read();
if(!res.empty())
{
return res[0]["value"]=="true";
}
}
return false;
}
std::string Helper::remoteAddr()
{
str_map::iterator it_remote = PARAMS->find("HTTP_X_FORWARDED_FOR");
if (it_remote != PARAMS->end())
{
if (it_remote->second.find(",") != std::string::npos)
{
return trim(getuntil(",", it_remote->second));
}
return it_remote->second;
}
return (*PARAMS)["REMOTE_ADDR"];
}
void Helper::startLogin(const std::string& remote_addr)
{
if (!failedLoginRateLimit())
return;
IScopedLock lock(login_wait_mutex);
while (logging_in.find(remote_addr) != logging_in.end())
{
login_wait_cond->wait(&lock);
}
}
void Helper::stopLogin(const std::string& remote_addr)
{
if (!failedLoginRateLimit())
return;
IScopedLock lock(login_wait_mutex);
logging_in.erase(remote_addr);
login_wait_cond->notify_all();
}
bool Helper::rateLimited(const std::string& remote_addr)
{
if (!failedLoginRateLimit())
return false;
IScopedReadLock read_lock(rate_limit_mutex);
if (banned_ips.find(remote_addr) != banned_ips.end())
return true;
return false;
}
void Helper::addToRateLimit(const std::string& remote_addr)
{
if (!failedLoginRateLimit())
return;
IScopedWriteLock wr_lock(rate_limit_mutex);
const int64 bucket = Server->getTimeMS() / 10000;
++rates_per_bucket[bucket][remote_addr];
int64 failed_logins = 0;
for (rate_limit_map::iterator it_bucket = rates_per_bucket.begin();
it_bucket != rates_per_bucket.end(); ++it_bucket)
{
std::map<std::string, int64>::iterator it_ip = it_bucket->second.find(remote_addr);
if (it_ip != it_bucket->second.end())
{
failed_logins += it_ip->second;
if (failed_logins > 10)
{
banned_ips[remote_addr] = Server->getTimeMS();
return;
}
}
}
}
void Helper::rateLimitTimeout()
{
const int64 keep_buckets = 4;
const int64 bucket_size = 10;
const int64 ban_timeout = 10 * 60 * 1000;
while (true)
{
Server->wait(bucket_size * 1000);
const int64 curr_bucket = Server->getTimeMS() / (bucket_size * 1000);
const int64 min_bucket = curr_bucket - keep_buckets;
IScopedWriteLock wr_lock(rate_limit_mutex);
for (rate_limit_map::iterator it_bucket = rates_per_bucket.begin();
it_bucket != rates_per_bucket.end();)
{
if (it_bucket->first < min_bucket)
{
rate_limit_map::iterator it_curr = it_bucket;
++it_bucket;
rates_per_bucket.erase(it_curr);
}
else
{
break;
}
}
const int64 ctime = Server->getTimeMS();
for (std::map<std::string, int64>::iterator it = banned_ips.begin();
it != banned_ips.end(); )
{
if (ctime - it->second > ban_timeout)
{
std::map<std::string, int64>::iterator it_curr = it;
++it;
banned_ips.erase(it_curr);
}
else
{
++it;
}
}
}
}
bool Helper::ldapLogin( const std::string &username, const std::string &password,
std::string* ret_errmsg, std::string* rights, bool dry_login)
{
if(url_fak==NULL)
{
return false;
}
ServerSettings settings(getDatabase());
SLDAPSettings ldap_settings = settings.getLDAPSettings();
if (!ldap_settings.login_enabled)
{
return false;
}
std::string sanitized_username = username;
std::string to_sanitize = "\"[]:;|=+*?<>/\\,";
for(size_t i=0;i<sanitized_username.size();++i)
{
if(std::find(to_sanitize.begin(), to_sanitize.end(), sanitized_username[i])!=to_sanitize.end())
{
sanitized_username[i]='_';
}
}
std::string group_class_query = greplace("{USERNAME}", sanitized_username, (ldap_settings.group_class_query));
std::string ldap_query = "ldap://" + ldap_settings.server_name +
(ldap_settings.server_port>0?(":" + convert(ldap_settings.server_port)):"") +
"/" + (group_class_query);
std::string errmsg;
std::vector<std::multimap<std::string, std::string> > data = url_fak->queryLDAP(ldap_query, ldap_settings.username_prefix+(username)+ldap_settings.username_suffix,
(password), &errmsg);
if(data.empty())
{
if(!errmsg.empty())
{
Server->Log("Login via LDAP failed: "+errmsg, LL_ERROR);
if(ret_errmsg)
{
*ret_errmsg = errmsg;
}
}
return false;
}
else
{
if(data.size()!=1)
{
Server->Log("LDAP query returned "+convert(data.size())+" items, but should return only one. Login failed.", LL_ERROR);
if(ret_errmsg)
{
*ret_errmsg="LDAP query returned more than one result";
}
return false;
}
IQuery* q = getDatabase()->Prepare("SELECT clientid FROM users_on_client WHERE username=?");
q->Bind(strlower(ldap_settings.username_prefix + username + ldap_settings.username_suffix));
db_results db_res = q->Read();
q->Reset();
std::string autoclients;
for(size_t i=0;i<db_res.size();++i)
{
if(!autoclients.empty()) autoclients+=",";
autoclients+=db_res[i]["clientid"];
}
std::multimap<std::string, std::string> sdata = data[0];
std::string str_ldap_rights;
std::multimap<std::string, std::string>::iterator it = sdata.find(ldap_settings.group_key_name);
while(it!=sdata.end() && it->first == ldap_settings.group_key_name)
{
for(std::map<std::string, std::string>::iterator it_rights=
ldap_settings.group_rights_map.begin();it_rights!=ldap_settings.group_rights_map.end();
++it_rights)
{
if(amatch((it->second).c_str(),
it_rights->first.c_str()))
{
str_ldap_rights = greplace("{AUTOCLIENTS}", autoclients, (it_rights->second));
break;
}
}
++it;
}
if(str_ldap_rights.empty())
{
std::multimap<std::string, std::string>::iterator it = sdata.find(ldap_settings.class_key_name);
while(it!=sdata.end() && it->first == ldap_settings.class_key_name)
{
for(std::map<std::string, std::string>::iterator it_rights=
ldap_settings.class_rights_map.begin();it_rights!=ldap_settings.class_rights_map.end();
++it_rights)
{
if(amatch((it->second).c_str(),
it_rights->first.c_str()))
{
str_ldap_rights = greplace("{AUTOCLIENTS}", autoclients, (it_rights->second));
break;
}
}
++it;
}
}
if(!str_ldap_rights.empty() && !dry_login)
{
ldap_rights = parseRightsString(str_ldap_rights);
}
if(!str_ldap_rights.empty() && session!=NULL && !dry_login)
{
session->mStr["ldap_rights"] = str_ldap_rights;
}
q= getDatabase()->Prepare("SELECT token FROM user_tokens WHERE username = ?");
q->Bind(strlower(ldap_settings.username_prefix + username + ldap_settings.username_suffix));
db_res = q->Read();
q->Reset();
std::string fileaccesstokens;
for(size_t i=0;i<db_res.size();++i)
{
if(!fileaccesstokens.empty()) fileaccesstokens+=";";
fileaccesstokens+=db_res[i]["token"];
}
if(!fileaccesstokens.empty() && !dry_login)
{
session->mStr["fileaccesstokens"]=fileaccesstokens;
}
if(rights)
{
*rights = str_ldap_rights;
}
return !str_ldap_rights.empty();
}
}
std::map<std::string, std::string> Helper::parseRightsString( const std::string& rights )
{
std::vector<std::string> toks;
Tokenize(rights, toks, ",");
std::map<std::string, std::string> ret;
for(size_t i=0;i<toks.size();++i)
{
std::string domain = getuntil("=", toks[i]);
std::string right = getafter("=", toks[i]);
ret[domain]=right;
}
return ret;
}