forked from pgbouncer/pgbouncer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.c
1278 lines (1152 loc) · 35.9 KB
/
client.c
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* PgBouncer - Lightweight connection pooler for PostgreSQL.
*
* Copyright (c) 2007-2009 Marko Kreen, Skype Technologies OÜ
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Client connection handling
*/
#include "bouncer.h"
#include "pam.h"
#include "scram.h"
#include "common/builtins.h"
#include <usual/pgutil.h>
static const char *hdr2hex(const struct MBuf *data, char *buf, unsigned buflen)
{
const uint8_t *bin = data->data + data->read_pos;
unsigned int dlen;
dlen = mbuf_avail_for_read(data);
return bin2hex(bin, dlen, buf, buflen);
}
/*
* Get authentication database for the current client. The order of preference is:
* client->db->auth_dbname: per client authentication database
* cf_auth_dbname: global authentication database
* client->db: client database
*
* NOTE: if the authentication database is not found or it is disabled, client
* will be disconnected.
*/
PgDatabase *prepare_auth_database(PgSocket *client)
{
PgDatabase *auth_db = NULL;
const char *auth_dbname = client->db->auth_dbname ? client->db->auth_dbname : cf_auth_dbname;
if (!auth_dbname) {
auth_db = client->db;
} else {
auth_db = find_or_register_database(client, auth_dbname);
}
if (!auth_db) {
slog_error(client, "authentication database \"%s\" is not configured.", auth_dbname);
disconnect_client(client, true, "bouncer config error");
return NULL;
}
if (auth_db->db_disabled) {
disconnect_client(
client,
true,
"authentication database \"%s\" is disabled",
auth_dbname);
return NULL;
}
if (auth_db->admin) {
slog_error(client, "cannot use the reserved \"%s\" database as an auth_dbname", auth_db->dbname);
disconnect_client(client, true, "bouncer config error");
return NULL;
}
return auth_db;
}
static bool check_client_passwd(PgSocket *client, const char *passwd)
{
PgUser *user = client->login_user;
int auth_type = client->client_auth_type;
if (user->mock_auth)
return false;
/* disallow empty passwords */
if (!*user->passwd)
return false;
switch (auth_type) {
case AUTH_PLAIN:
switch (get_password_type(user->passwd)) {
case PASSWORD_TYPE_PLAINTEXT:
return strcmp(user->passwd, passwd) == 0;
case PASSWORD_TYPE_MD5: {
char md5[MD5_PASSWD_LEN + 1];
pg_md5_encrypt(passwd, user->name, strlen(user->name), md5);
return strcmp(user->passwd, md5) == 0;
}
case PASSWORD_TYPE_SCRAM_SHA_256:
return scram_verify_plain_password(client, user->name, passwd, user->passwd);
default:
return false;
}
case AUTH_MD5: {
char *stored_passwd;
char md5[MD5_PASSWD_LEN + 1];
if (strlen(passwd) != MD5_PASSWD_LEN)
return false;
/*
* The client sends
* 'md5'+md5(md5(password+username)+salt). The stored
* password is either 'md5'+md5(password+username) or
* plain text. If the latter, we compute the inner
* md5() call first.
*/
if (get_password_type(user->passwd) == PASSWORD_TYPE_PLAINTEXT) {
pg_md5_encrypt(user->passwd, user->name, strlen(user->name), md5);
stored_passwd = md5;
} else {
stored_passwd = user->passwd;
}
pg_md5_encrypt(stored_passwd + 3, (char *)client->tmp_login_salt, 4, md5);
return strcmp(md5, passwd) == 0;
}
}
return false;
}
static bool send_client_authreq(PgSocket *client)
{
int res;
int auth_type = client->client_auth_type;
if (auth_type == AUTH_MD5) {
uint8_t saltlen = 4;
get_random_bytes((void *)client->tmp_login_salt, saltlen);
SEND_generic(res, client, 'R', "ib", AUTH_MD5, client->tmp_login_salt, saltlen);
} else if (auth_type == AUTH_PLAIN || auth_type == AUTH_PAM) {
SEND_generic(res, client, 'R', "i", AUTH_PLAIN);
} else if (auth_type == AUTH_SCRAM_SHA_256) {
SEND_generic(res, client, 'R', "iss", AUTH_SASL, "SCRAM-SHA-256", "");
} else {
return false;
}
if (!res) {
slog_noise(client, "No authentication response received");
disconnect_client(client, false, "failed to send auth req");
} else {
slog_noise(client, "Auth request sent successfully");
}
return res;
}
static void start_auth_query(PgSocket *client, const char *username)
{
int res;
PktBuf *buf;
/* have to fetch user info from db */
PgDatabase *auth_db = prepare_auth_database(client);
if (!auth_db)
return;
client->pool = get_pool(auth_db, client->db->auth_user);
if (!find_server(client)) {
client->wait_for_user_conn = true;
return;
}
slog_noise(client, "doing auth_conn query");
client->wait_for_user_conn = false;
client->wait_for_user = true;
if (!sbuf_pause(&client->sbuf)) {
release_server(client->link);
disconnect_client(client, true, "pause failed");
return;
}
client->link->ready = false;
res = 0;
buf = pktbuf_dynamic(512);
if (buf) {
pktbuf_write_ExtQuery(buf, cf_auth_query, 1, username);
res = pktbuf_send_immediate(buf, client->link);
pktbuf_free(buf);
/*
* Should do instead:
* res = pktbuf_send_queued(buf, client->link);
* but that needs better integration with SBuf.
*/
}
if (!res)
disconnect_server(client->link, false, "unable to send auth_query");
client->expect_rfq_count++;
}
static bool login_via_cert(PgSocket *client)
{
struct tls *tls = client->sbuf.tls;
if (!tls) {
slog_error(client, "TLS connection required");
goto fail;
}
if (!tls_peer_cert_provided(client->sbuf.tls)) {
slog_error(client, "TLS client certificate required");
goto fail;
}
if (client->login_user->mock_auth)
goto fail;
log_debug("TLS cert login: %s", tls_peer_cert_subject(client->sbuf.tls));
if (!tls_peer_cert_contains_name(client->sbuf.tls, client->login_user->name)) {
slog_error(client, "TLS certificate name mismatch");
goto fail;
}
/* login successful */
return finish_client_login(client);
fail:
disconnect_client(client, true, "certificate authentication failed");
return false;
}
static bool login_as_unix_peer(PgSocket *client)
{
if (!pga_is_unix(&client->remote_addr))
goto fail;
if (client->login_user->mock_auth)
goto fail;
if (!check_unix_peer_name(sbuf_socket(&client->sbuf), client->login_user->name))
goto fail;
return finish_client_login(client);
fail:
disconnect_client(client, true, "unix socket login rejected");
return false;
}
static bool finish_set_pool(PgSocket *client, bool takeover)
{
bool ok = false;
int auth;
if (!client->login_user->mock_auth && !client->db->fake) {
PgUser *pool_user;
if (client->db->forced_user)
pool_user = client->db->forced_user;
else
pool_user = client->login_user;
client->pool = get_pool(client->db, pool_user);
if (!client->pool) {
disconnect_client(client, true, "no memory for pool");
return false;
}
}
if (cf_log_connections) {
if (client->sbuf.tls) {
char infobuf[96] = "";
tls_get_connection_info(client->sbuf.tls, infobuf, sizeof infobuf);
slog_info(client, "login attempt: db=%s user=%s tls=%s replication=%s",
client->db->name,
client->login_user->name,
infobuf,
replication_type_parameters[client->replication]);
} else {
slog_info(client, "login attempt: db=%s user=%s tls=no replication=%s",
client->db->name, client->login_user->name,
replication_type_parameters[client->replication]);
}
}
if (takeover)
return true;
if (client->pool && client->pool->db->admin) {
if (!admin_post_login(client))
return false;
}
if (client->own_user)
return finish_client_login(client);
auth = cf_auth_type;
if (auth == AUTH_HBA) {
auth = hba_eval(
parsed_hba,
&client->remote_addr,
!!client->sbuf.tls,
client->replication,
client->db->name,
client->login_user->name);
}
if (auth == AUTH_MD5) {
if (get_password_type(client->login_user->passwd) == PASSWORD_TYPE_SCRAM_SHA_256)
auth = AUTH_SCRAM_SHA_256;
}
/* remember method */
client->client_auth_type = auth;
switch (auth) {
case AUTH_ANY:
ok = finish_client_login(client);
break;
case AUTH_TRUST:
if (client->login_user->mock_auth)
disconnect_client(client, true, "\"trust\" authentication failed");
else
ok = finish_client_login(client);
break;
case AUTH_PLAIN:
case AUTH_MD5:
case AUTH_PAM:
case AUTH_SCRAM_SHA_256:
ok = send_client_authreq(client);
break;
case AUTH_CERT:
ok = login_via_cert(client);
break;
case AUTH_PEER:
ok = login_as_unix_peer(client);
break;
default:
disconnect_client(client, true, "login rejected");
ok = false;
}
return ok;
}
bool set_pool(PgSocket *client, const char *dbname, const char *username, const char *password, bool takeover)
{
Assert((password && takeover) || (!password && !takeover));
/* find database */
client->db = find_or_register_database(client, dbname);
if (!client->db) {
client->db = calloc(1, sizeof(*client->db));
client->db->fake = true;
strlcpy(client->db->name, dbname, sizeof(client->db->name));
}
if (client->db->admin) {
if (admin_pre_login(client, username))
return finish_set_pool(client, takeover);
}
/* avoid dealing with invalid data below, and give an
* appropriate error message */
if (strlen(username) >= MAX_USERNAME) {
disconnect_client(client, true, "username too long");
if (cf_log_connections)
slog_info(client, "login failed: db=%s user=%s", dbname, username);
return false;
}
if (password && strlen(password) >= MAX_PASSWORD) {
disconnect_client(client, true, "password too long");
if (cf_log_connections)
slog_info(client, "login failed: db=%s user=%s", dbname, username);
return false;
}
/* find user */
if (cf_auth_type == AUTH_ANY) {
/* ignore requested user */
if (client->db->forced_user == NULL) {
slog_error(client, "auth_type=any requires forced user");
disconnect_client(client, true, "bouncer config error");
return false;
}
client->login_user = client->db->forced_user;
} else if (cf_auth_type == AUTH_PAM) {
if (client->db->auth_user) {
slog_error(client, "PAM can't be used together with database authentication");
disconnect_client(client, true, "bouncer config error");
return false;
}
/* Password will be set after successful authentication when not in takeover mode */
client->login_user = add_pam_user(username, password);
if (!client->login_user) {
slog_error(client, "set_pool(): failed to allocate new PAM user");
disconnect_client(client, true, "bouncer resources exhaustion");
return false;
}
} else {
client->login_user = find_user(username);
if (!client->login_user) {
/*
* If the login user specified by the client
* does not exist, check if an auth_user is
* set and if so send off an auth_query. If
* no auth_user is set for the db, see if the
* global auth_user is set and use that.
*/
if (!client->db->auth_user && cf_auth_user) {
client->db->auth_user = find_user(cf_auth_user);
if (!client->db->auth_user)
client->db->auth_user = add_user(cf_auth_user, "");
}
if (client->db->auth_user) {
if (client->db->fake) {
slog_debug(client, "not running auth_query because database is fake");
} else {
if (takeover) {
client->login_user = add_db_user(client->db, username, password);
return finish_set_pool(client, takeover);
}
start_auth_query(client, username);
return false;
}
}
slog_info(client, "no such user: %s", username);
client->login_user = calloc(1, sizeof(*client->login_user));
client->login_user->mock_auth = true;
safe_strcpy(client->login_user->name, username, sizeof(client->login_user->name));
}
}
return finish_set_pool(client, takeover);
}
bool handle_auth_query_response(PgSocket *client, PktHdr *pkt)
{
uint16_t columns;
uint32_t length;
const char *username, *password;
PgUser user;
PgSocket *server = client->link;
switch (pkt->type) {
case 'T': /* RowDescription */
if (!mbuf_get_uint16be(&pkt->data, &columns)) {
disconnect_server(server, false, "bad packet");
return false;
}
if (columns != 2u) {
disconnect_server(server, false, "expected 2 columns from auth_query, not %hu", columns);
return false;
}
break;
case 'D': /* DataRow */
memset(&user, 0, sizeof(user));
if (!mbuf_get_uint16be(&pkt->data, &columns)) {
disconnect_server(server, false, "bad packet");
return false;
}
if (columns != 2u) {
disconnect_server(server, false, "expected 2 columns from auth_query, not %hu", columns);
return false;
}
if (!mbuf_get_uint32be(&pkt->data, &length)) {
disconnect_server(server, false, "bad packet");
return false;
}
if (length == (uint32_t)-1) {
disconnect_server(server, false, "auth_query response contained null user name");
return false;
}
if (!mbuf_get_chars(&pkt->data, length, &username)) {
disconnect_server(server, false, "bad packet");
return false;
}
if (sizeof(user.name) - 1 < length)
length = sizeof(user.name) - 1;
memcpy(user.name, username, length);
if (!mbuf_get_uint32be(&pkt->data, &length)) {
disconnect_server(server, false, "bad packet");
return false;
}
if (length == (uint32_t)-1) {
/*
* NULL - set an md5 password with an impossible value,
* so that nothing will ever match
*/
password = "md5";
length = 3;
} else {
if (!mbuf_get_chars(&pkt->data, length, &password)) {
disconnect_server(server, false, "bad packet");
return false;
}
}
if (sizeof(user.passwd) - 1 < length)
length = sizeof(user.passwd) - 1;
memcpy(user.passwd, password, length);
client->login_user = add_db_user(client->db, user.name, user.passwd);
if (!client->login_user) {
disconnect_server(server, false, "unable to allocate new user for auth");
return false;
}
break;
case 'N': /* NoticeResponse */
break;
case 'C': /* CommandComplete */
break;
case '1': /* ParseComplete */
break;
case '2': /* BindComplete */
break;
case 'S': /* ParameterStatus */
break;
case 'Z': /* ReadyForQuery */
sbuf_prepare_skip(&client->link->sbuf, pkt->len);
if (!client->login_user) {
if (cf_log_connections)
slog_info(client, "login failed: db=%s", client->db->name);
/*
* TODO: Currently no mock authentication when
* using auth_query/auth_user; we just abort
* with a revealing message to the client.
* The main problem is that at this point we
* don't know the original user name anymore
* to do that. As a workaround, the
* auth_query could be written in a way that
* it returns a fake user and password if the
* requested user doesn't exist.
*/
disconnect_client(client, true, "no such user");
} else {
slog_noise(client, "auth query complete");
client->link->resetting = true;
sbuf_continue(&client->sbuf);
}
/*
* either sbuf_continue or disconnect_client could disconnect the server
* way down in their bowels of other callbacks. so check that, and
* return appropriately (similar to reuse_on_release)
*/
if (server->state == SV_FREE || server->state == SV_JUSTFREE)
return false;
return true;
case 'E': /* ErrorResponse */
disconnect_server(server, false, "error response from auth_query");
return false;
default:
disconnect_server(server, false, "unexpected response from auth_query");
return false;
}
sbuf_prepare_skip(&server->sbuf, pkt->len);
return true;
}
/*
* read_escaped_token reads a token that might be escaped using backslashes
* from the escaped_string_ptr. The token is written in unescaped form to the
* unescaped_token buffer. escape_string_ptr is set to the character right
* after the token.
*/
static bool read_escaped_token(const char **escaped_string_ptr, struct MBuf *unescaped_token)
{
const char *position = *escaped_string_ptr;
const char *unwritten_start = position;
while (*position) {
if (*position == '\\') {
if (!mbuf_write(unescaped_token, unwritten_start, position - unwritten_start))
return false;
position++;
unwritten_start = position;
if (!*position)
break;
} else if (isspace(*position)) {
break;
}
position++;
}
if (!mbuf_write(unescaped_token, unwritten_start, position - unwritten_start))
return false;
if (!mbuf_write_byte(unescaped_token, '\0'))
return false;
*escaped_string_ptr = position;
return true;
}
/*
* set_startup_options takes the value of the "options" startup parameter
* and uses it to set the parameters that are embedded in this value.
*
* It only supports the following type of PostgreSQL command line argument:
* -c config=value
*
* The reason that we don't support all arguments is to keep the parsing simple
* an this is by far the argument that's most commonly used in practice in the
* options startup parameter. Also all other postgres command line arguments
* can be rewritten to this form.
*
* NOTE: it's possible to supply "options" in ignore_startup_parameters, which
* results in all unknown options being ignored. This is for historical reasons,
* because it was supported like that in the past.
*/
static bool set_startup_options(PgSocket *client, const char *options)
{
char arg_buf[400];
struct MBuf arg;
const char *position = options;
if (client->replication) {
/*
* Since replication clients will be bound 1-to-1 to a server
* connection, we can support any configuration flags and
* fields in the options startup parameter. Because we can
* simply send the exact same value for the options parameter
* when opening the replication connection to the server. This
* allows us to also support GUCs that don't have the
* GUC_REPORT flag, specifically extra_float_digits which is a
* configuration that is set by CREATE SUBSCRIPTION in the
* options parameter.
*/
client->startup_options = strdup(options);
if (!client->startup_options)
disconnect_client(client, true, "out of memory");
return true;
}
mbuf_init_fixed_writer(&arg, arg_buf, sizeof(arg_buf));
slog_debug(client, "received options: %s", options);
while (*position) {
const char *key_string, *value_string;
char *equals;
mbuf_rewind_writer(&arg);
position = cstr_skip_ws((char *) position);
if (strncmp("-c", position, 2) != 0)
goto fail;
position += 2;
position = cstr_skip_ws((char *) position);
if (!read_escaped_token(&position, &arg)) {
disconnect_client(client, true, "unsupported options startup parameter: parameter too long");
return false;
}
equals = strchr((char *) arg.data, '=');
if (!equals)
goto fail;
*equals = '\0';
key_string = (const char *) arg.data;
value_string = (const char *) equals + 1;
if (varcache_set(&client->vars, key_string, value_string)) {
slog_debug(client, "got var from options: %s=%s", key_string, value_string);
} else if (strlist_contains(cf_ignore_startup_params, key_string) || strlist_contains(cf_ignore_startup_params, "options")) {
slog_debug(client, "ignoring startup parameter from options: %s=%s", key_string, value_string);
} else {
slog_warning(client, "unsupported startup parameter in options: %s=%s", key_string, value_string);
disconnect_client(client, true, "unsupported startup parameter in options: %s", key_string);
return false;
}
}
return true;
fail:
disconnect_client(client, true, "unsupported options startup parameter: only '-c config=val' is allowed");
return false;
}
static void set_appname(PgSocket *client, const char *app_name)
{
char buf[400], abuf[300];
const char *details;
if (cf_application_name_add_host) {
/* give app a name */
if (!app_name)
app_name = "app";
/* add details */
details = pga_details(&client->remote_addr, abuf, sizeof(abuf));
snprintf(buf, sizeof(buf), "%s - %s", app_name, details);
app_name = buf;
}
if (app_name) {
slog_debug(client, "using application_name: %s", app_name);
varcache_set(&client->vars, "application_name", app_name);
}
}
/*
* set_replication sets the replication field on the client according the given
* replicationString.
*/
static bool set_replication(PgSocket *client, const char *replicationString)
{
bool replicationBool = false;
if (strcmp(replicationString, "database") == 0) {
client->replication = REPLICATION_LOGICAL;
return true;
}
if (!parse_bool(replicationString, &replicationBool)) {
return false;
}
client->replication = replicationBool ? REPLICATION_PHYSICAL : REPLICATION_NONE;
return true;
}
static bool decide_startup_pool(PgSocket *client, PktHdr *pkt)
{
const char *username = NULL, *dbname = NULL;
const char *key, *val;
bool ok;
bool appname_found = false;
unsigned original_read_pos = pkt->data.read_pos;
/*
* First check if we're dealing with a replication connection. Because for
* those we support some additional things when parsing the startup
* parameters, specifically we support any arguments in the options startup
* packet.
*/
while (1) {
ok = mbuf_get_string(&pkt->data, &key);
if (!ok || *key == 0)
break;
ok = mbuf_get_string(&pkt->data, &val);
if (!ok)
break;
if (strcmp(key, "replication") == 0) {
slog_debug(client, "got var: %s=%s", key, val);
set_replication(client, val);
}
}
pkt->data.read_pos = original_read_pos;
while (1) {
ok = mbuf_get_string(&pkt->data, &key);
if (!ok || *key == 0)
break;
ok = mbuf_get_string(&pkt->data, &val);
if (!ok)
break;
if (strcmp(key, "database") == 0) {
slog_debug(client, "got var: %s=%s", key, val);
dbname = val;
} else if (strcmp(key, "user") == 0) {
slog_debug(client, "got var: %s=%s", key, val);
username = val;
} else if (strcmp(key, "options") == 0) {
if (!set_startup_options(client, val))
return false;
} else if (strcmp(key, "application_name") == 0) {
set_appname(client, val);
appname_found = true;
} else if (strcmp(key, "replication") == 0) {
/* do nothing, already checked in the previous loop */
} else if (varcache_set(&client->vars, key, val)) {
slog_debug(client, "got var: %s=%s", key, val);
} else if (strlist_contains(cf_ignore_startup_params, key)) {
slog_debug(client, "ignoring startup parameter: %s=%s", key, val);
} else {
slog_warning(client, "unsupported startup parameter: %s=%s", key, val);
disconnect_client(client, true, "unsupported startup parameter: %s", key);
return false;
}
}
if (!username || !username[0]) {
disconnect_client(client, true, "no username supplied");
return false;
}
/* if missing dbname, default to username */
if (!dbname || !dbname[0])
dbname = username;
/* create application_name if requested */
if (!appname_found)
set_appname(client, NULL);
/* check if limit allows, don't limit admin db
nb: new incoming conn will be attached to PgSocket, thus
get_active_client_count() counts it */
if (get_active_client_count() > cf_max_client_conn) {
if (strcmp(dbname, "pgbouncer") != 0) {
disconnect_client(client, true, "no more connections allowed (max_client_conn)");
return false;
}
}
/* find pool */
return set_pool(client, dbname, username, NULL, false);
}
static bool scram_client_first(PgSocket *client, uint32_t datalen, const uint8_t *data)
{
char *ibuf;
char *input;
int res;
PgUser *user = client->login_user;
ibuf = malloc(datalen + 1);
if (ibuf == NULL)
return false;
memcpy(ibuf, data, datalen);
ibuf[datalen] = '\0';
input = ibuf;
slog_debug(client, "SCRAM client-first-message = \"%s\"", input);
if (!read_client_first_message(client, input,
&client->scram_state.cbind_flag,
&client->scram_state.client_first_message_bare,
&client->scram_state.client_nonce))
goto failed;
if (!user->mock_auth) {
slog_debug(client, "stored secret = \"%s\"", user->passwd);
switch (get_password_type(user->passwd)) {
case PASSWORD_TYPE_MD5:
slog_error(client, "SCRAM authentication failed: user has MD5 secret");
goto failed;
case PASSWORD_TYPE_PLAINTEXT:
case PASSWORD_TYPE_SCRAM_SHA_256:
break;
}
}
if (!build_server_first_message(&client->scram_state, user->name, user->mock_auth ? NULL : user->passwd))
goto failed;
slog_debug(client, "SCRAM server-first-message = \"%s\"", client->scram_state.server_first_message);
SEND_generic(res, client, 'R', "ib",
AUTH_SASL_CONT,
client->scram_state.server_first_message,
strlen(client->scram_state.server_first_message));
free(ibuf);
return res;
failed:
free(ibuf);
return false;
}
static bool scram_client_final(PgSocket *client, uint32_t datalen, const uint8_t *data)
{
char *ibuf;
char *input;
const char *client_final_nonce = NULL;
char *proof = NULL;
char *server_final_message;
int res;
ibuf = malloc(datalen + 1);
if (ibuf == NULL)
return false;
memcpy(ibuf, data, datalen);
ibuf[datalen] = '\0';
input = ibuf;
slog_debug(client, "SCRAM client-final-message = \"%s\"", input);
if (!read_client_final_message(client, data, input,
&client_final_nonce,
&proof))
goto failed;
slog_debug(client, "SCRAM client-final-message-without-proof = \"%s\"",
client->scram_state.client_final_message_without_proof);
if (!verify_final_nonce(&client->scram_state, client_final_nonce)) {
slog_error(client, "invalid SCRAM response (nonce does not match)");
goto failed;
}
if (!verify_client_proof(&client->scram_state, proof)
|| !client->login_user) {
slog_error(client, "password authentication failed");
goto failed;
}
server_final_message = build_server_final_message(&client->scram_state);
if (!server_final_message)
goto failed;
slog_debug(client, "SCRAM server-final-message = \"%s\"", server_final_message);
SEND_generic(res, client, 'R', "ib",
AUTH_SASL_FIN,
server_final_message,
strlen(server_final_message));
free(server_final_message);
free(proof);
free(ibuf);
return res;
failed:
free(proof);
free(ibuf);
return false;
}
/* decide on packets of client in login phase */
static bool handle_client_startup(PgSocket *client, PktHdr *pkt)
{
const char *passwd;
const uint8_t *key;
bool ok;
bool is_unix = pga_is_unix(&client->remote_addr);
SBuf *sbuf = &client->sbuf;
/* don't tolerate partial packets */
if (incomplete_pkt(pkt)) {
disconnect_client(client, true, "client sent partial pkt in startup phase");
return false;
}
if (client->wait_for_welcome || client->wait_for_auth) {
if (finish_client_login(client)) {
/* the packet was already parsed */
sbuf_prepare_skip(sbuf, pkt->len);
return true;
} else {
return false;
}
}
switch (pkt->type) {
case PKT_SSLREQ:
slog_noise(client, "C: req SSL");
if (client->sbuf.tls) {
disconnect_client(client, false, "SSL req inside SSL");
return false;
}
if (client_accept_sslmode != SSLMODE_DISABLED && !is_unix) {
slog_noise(client, "P: SSL ack");
if (!sbuf_answer(&client->sbuf, "S", 1)) {
disconnect_client(client, false, "failed to ack SSL");
return false;
}
if (!sbuf_tls_accept(&client->sbuf)) {
disconnect_client(client, false, "failed to accept SSL");
return false;
}
break;
}
/* reject SSL attempt */
slog_noise(client, "P: nak");
if (!sbuf_answer(&client->sbuf, "N", 1)) {
disconnect_client(client, false, "failed to nak SSL");
return false;
}
break;
case PKT_GSSENCREQ:
/* reject GSS encryption attempt */
slog_noise(client, "C: req GSS enc");
if (!sbuf_answer(&client->sbuf, "N", 1)) {
disconnect_client(client, false, "failed to nak GSS enc");
return false;
}
break;
case PKT_STARTUP_V2:
disconnect_client(client, true, "old V2 protocol not supported");
return false;
case PKT_STARTUP:
/* require SSL except on unix socket */
if (client_accept_sslmode >= SSLMODE_REQUIRE && !client->sbuf.tls && !is_unix) {
disconnect_client(client, true, "SSL required");
return false;
}
if (client->pool && !client->wait_for_user_conn && !client->wait_for_user) {
disconnect_client(client, true, "client re-sent startup pkt");
return false;
}
if (client->wait_for_user) {
client->wait_for_user = false;
if (!finish_set_pool(client, false))
return false;
} else if (!decide_startup_pool(client, pkt)) {
return false;
}
break;
case 'p': /* PasswordMessage, SASLInitialResponse, or SASLResponse */
/* too early */
if (!client->login_user) {
disconnect_client(client, true, "client password pkt before startup packet");
return false;
}
if (client->client_auth_type == AUTH_SCRAM_SHA_256) {
const char *mech;
uint32_t length;
const uint8_t *data;
if (!client->scram_state.server_nonce) {
/* process as SASLInitialResponse */
if (!mbuf_get_string(&pkt->data, &mech))