forked from sweetums/SASL-OAuth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoauth_new.c
1608 lines (1393 loc) · 46.9 KB
/
oauth_new.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
/* Oauth SASL plugin
* Bill Mills
* $Id: $
*
* Copyright (c) 2010, Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* See accompanying LICENSE file for terms.
*
*/
#include <config.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sasl.h>
#include <saslplug.h>
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <curl/curl.h>
#include <curl/easy.h>
#include <jansson.h>
#include "plugin_common.h"
#include "oauth_validate.h"
#ifdef macintosh
#include <sasl_oauth_plugin_decl.h>
#endif
char *base64(const unsigned char *input, int length);
int base64d(const unsigned char *input, int length, char **outbuf);
#define SASL_UTIL_MALLOC sparams->utils->malloc
#define SASL_UTIL_FREE sparams->utils->free
#define MECH_NAME "OAUTHNEW"
#define MECH_VERSION 0
#define DEFAULT_VALIDATOR "oauth_validate"
#define CSTATE_NEW 0 /* don't have anything yet. */
#define CSTATE_DISCOVER 1 /* sent a discovery request */
#define CSTATE_TOKEN 2 /* have discovery information,
** now we might need to fetch
** tokens, or we might have a
** valid token already
*/
#define OAUTH_MAX_DISCOVER 4096
#define ERRBUFFLEN 128
#define DISCOVERY_HDR_BANNER "HTTP/1.1 401 Unauthorized\r\n"
#define HTTP_RPY_1_1 "HTTP/1.1 "
#define HTTP_HDR_BANNER "GET / HTTP/1.1\r\n"
#define WWW_AUTHENTICATE "WWW-Authenticate: Token "
#define HDR_AUTH_STR "\r\nAuthorization: "
#define HDR_USER_STR "\r\nUser: "
#define HDR_HOST_STR "\r\nHost: "
#define DISCOVERY_HDR_AURI "auth_uri=\""
#define DISCOVERY_HDR_TURI "refresh_uri=\""
#define DISCOVERY_HDR_SCOPE "scope=\""
#define DISCOVERY_HDR_ERROR "error=\""
#define JSON_TAG_USERNAME "username"
#define JSON_TAG_REFRESH "refresh"
#define JSON_TAG_ACCESS "access"
#define JSON_TAG_ACCESS_EXPIRES "access_expires"
#define JSON_TAG_AUTH_URI "auth_uri"
#define JSON_TAG_REFRESH_URI "refresh_uri"
int oauth_client_mech_step_disco(void *conn_context,
sasl_client_params_t *params,
const char *serverin,
unsigned serverinlen,
sasl_interact_t **prompt_need,
const char **clientout,
unsigned *clientoutlen,
sasl_out_params_t *oparams);
int oauth_client_mech_step_token(void *conn_context,
sasl_client_params_t *params,
const char *serverin,
unsigned serverinlen,
sasl_interact_t **prompt_need,
const char **clientout,
unsigned *clientoutlen,
sasl_out_params_t *oparams);
/***************************** Common Section *****************************/
static const char plugin_id[] = "$Id: plain.c,v 1.64 2004/09/08 11:06:11 mel Exp $";
/***************************** Server Section *****************************/
typedef struct server_context {
int result;
char *name;
char *error;
char *validator_name;
sasl_auxprop_plug_t oauth_validator;
struct propctx *propctx;
} server_context_t;
/*
** Callback to store the oauth_validator auxprop plugin pointer
*/
void oauth_validator_info_callback_t (sasl_auxprop_plug_t *m,
sasl_info_callback_stage_t stage,
void *rock) {
server_context_t *text = (server_context_t *)rock;
switch (stage) {
case SASL_INFO_LIST_START:
case SASL_INFO_LIST_END:
break;
case SASL_INFO_LIST_MECH:
memcpy(&text->oauth_validator, m, sizeof(sasl_auxprop_plug_t));
break;
}
}
/*
** Mech initializer
*/
static int
oauth_server_mech_new(void *glob_context __attribute__((unused)),
sasl_server_params_t *sparams,
const char *challenge __attribute__((unused)),
unsigned challen __attribute__((unused)),
void **conn_context)
{
server_context_t *text;
const char *tmp;
int ret;
/* holds state are in */
text = sparams->utils->malloc(sizeof(server_context_t));
if (text == NULL) {
MEMERROR( sparams->utils );
return SASL_NOMEM;
}
memset(text, 0, sizeof(server_context_t));
text->result = SASL_BADPROT;
/* text->error = strdup("OAUTH mechanism: no transactions sent before ending."); */
*conn_context = text;
/*
** XXXXXX Should this really be in a more global palce and done just once?
** I don't think so because we can't do it on library init because the
** loading order may not be right for us.
**
** Get the name of our validation auxprop plugin and then find the
** handle to that plugin for use later.
*/
sparams->utils->getopt(sparams->utils->getopt_context, MECH_NAME,
"oauth_validator_mechanism", &tmp, NULL);
if(!tmp) {
if (!(tmp = strdup(DEFAULT_VALIDATOR))) return SASL_NOMEM;
}
/* need a prctx to use for holding authenticated user info */
if (NULL == (text->propctx = sparams->utils->prop_new(3)))
return SASL_NOMEM;
/*
** Now find our validator
*/
ret = auxprop_plugin_info(tmp, oauth_validator_info_callback_t, text);
if (!text->oauth_validator.auxprop_lookup) {
SETERROR(sparams->utils, "OAUTH: Counld not find oauth validator plugin.");
return SASL_FAIL;
}
/* */
return ret;
}
/*
** oauth_server_fmt_discovery
**
** Function to format the discovery info in the session.
*/
char *oauth_auth_uri = "http://frustration.corp.yahoo.com/oauth.php";
char *oauth_refresh_uri = "http://frustration.corp.yahoo.com/oauth.php";
char *oauth_server_scope = "";
int oauth_server_fmt_discovery(server_context_t *text,
sasl_server_params_t *sparams,
int ecode,
const char *error) {
const char *discover_format;
discover_format = "HTTP/1.1 %d Unauthorized\r\nWWW-Authenticate: Token realm=\"Service\", error=\"%s\", auth_uri=\"%s\", refresh_uri=\"%s\", scope=\"%s\"\r\n\r\n";
if (NULL == text->error) {
text->error = sparams->utils->malloc(OAUTH_MAX_DISCOVER +1);
if (text->error == NULL) {
MEMERROR(sparams->utils);
return SASL_NOMEM;
}
text->error[OAUTH_MAX_DISCOVER] = '\0';
/* Format the proper error/discovery info */
if (OAUTH_MAX_DISCOVER < snprintf(text->error, OAUTH_MAX_DISCOVER+1,
discover_format, ecode, error,
oauth_auth_uri, oauth_refresh_uri,
oauth_server_scope)) {
SETERROR(sparams->utils, "OAUTH: discovery information too long.");
return SASL_BUFOVER;
}
}
return SASL_OK;
}
/*
** oauth_server_mech_step
**
** Standard server plugin step handler.
*/
static int
oauth_server_mech_step(void *conn_context,
sasl_server_params_t *sparams,
const char *clientin,
unsigned clientinlen,
const char **serverout,
unsigned *serveroutlen,
sasl_out_params_t *oparams)
{
server_context_t *text = (server_context_t *)conn_context;
char *tmpstr;
int hdrlen = strlen(HDR_AUTH_STR);
int result, result2;
const struct propval *pv;
/*
** If we got nothing this indicates the end of the negotiation. This is the
** server's cue to send back whatever result state we have pending. Note that
** we're setting the default state as SASL_BADPROT in the mech_new step.
*/
if (clientinlen == 0) {
return text->result;
}
/*
** The basics here are that evrything requires an HTTP GET string and Host
** header.
*/
if ((0 != strncmp(clientin, HTTP_HDR_BANNER, strlen(HTTP_HDR_BANNER))) ||
(NULL == strstr(clientin, HDR_HOST_STR)) ||
(NULL == (tmpstr = strstr(clientin, HDR_AUTH_STR)))) {
SETERROR(sparams->utils, "OAUTH: GET banner, Host, and Authorization headers required.");
return SASL_BADPROT;
}
/*
** If we got here we have something to think about. Basically, if we get something
** in that looks kind of right we'll hand it off to be authenticated, otherwise
** we return discovery. In this very basic implementation, we're not actually
** doing variable discovery info.
**
** Simple to see if we have an empty Authorization header now.
*/
if (tmpstr[hdrlen] == '\r' && tmpstr[hdrlen+1] == '\n') {
/*
** format discovery info into text-error. We send 'discovery' as
** the error.
**
** XXXXXXX N.B. 'discovery' is not in the OAuth protocol right now.
*/
result = oauth_server_fmt_discovery(text, sparams, 401, "discovery");
if (SASL_OK != result)
return result;
/* take our error/discovery and send it. */
*serverout = text->error;
*serveroutlen = (unsigned) strlen(text->error);
/*
** At this point we've sent discovery information back to the user, at
** this point we set SASL_FAIL as our pending return value, which is
** strictly true since if you're querying discovery info and do nothing
** else authentication has failed.
*/
text->result = SASL_FAIL;
return SASL_CONTINUE;
}
/*
** If we get here it's a nominally valid, non-discovery request. Here
** we cal out to the validation plugin and see what we get.
**
** XXXXXXX is using a propctx local to the connection right here, or should it be sparams->propctx?
** we could use text->propctx. Also, I don't think the global context is right here.
*/
result = text->oauth_validator.auxprop_store(text->propctx, sparams, text->propctx,
clientin, clientinlen);
/*
** Failure means set the error state. We don't end because we give
** the client the opportunity to correct an expired token. We need to
** send back the proper error code.
*/
switch (result) {
case SASL_OK:
/*
** if we were able to store the credential that means validation succeeded,
** and the data we probably care about is now stored in the propctx in
** sparams.
**
** go ahead and finalize successfully.
**
** Several others are fatal.
*/
// prop_request(text->propctx, (const char**)names);
pv = prop_get(text->propctx);
while (pv && strcmp(OAUTH_VALIDATE_USERNAME, pv->name)) pv++;
if (!pv)
return SASL_FAIL;
result = sparams->canon_user(sparams->utils->conn, pv->values[0],
0, SASL_CU_AUTHID, oparams);
result = sparams->canon_user(sparams->utils->conn, pv->values[0],
0, SASL_CU_AUTHZID, oparams);
if (result != SASL_OK) return result;
/* set oparams, we succeeded */
oparams->doneflag = 1;
oparams->mech_ssf = 0;
oparams->maxoutbuf = 0;
oparams->encode_context = NULL;
oparams->encode = NULL;
oparams->decode_context = NULL;
oparams->decode = NULL;
oparams->param_version = 0;
return SASL_OK;
break;
case SASL_FAIL:
case SASL_BADPROT:
case SASL_NOMEM:
case SASL_BADAUTH:
// BAD_AUTH could be
// if (SASL_OK != oauth_server_fmt_discovery(text, sparams, 401, "invalid-token"))
return result;
break;
case SASL_EXPIRED:
if (SASL_OK != (result2 = oauth_server_fmt_discovery(text, sparams,
401, "expired-token")))
return result2;
break;
case SASL_NOAUTHZ:
/* using this for scope failure */
if (SASL_OK != (result2 = oauth_server_fmt_discovery(text, sparams,
403, "insufficient-scope")))
return result;
break;
text->result = result;
}
return SASL_CONTINUE;
}
static void oauth_server_mech_dispose(void *conn_context,
const sasl_utils_t *utils)
{
server_context_t *text = (server_context_t *) conn_context;
if (!text) return;
if (text->error) _plug_free_string(utils,&(text->error));
if (text->name) _plug_free_string(utils,&(text->name));
if (text->error) _plug_free_string(utils,&(text->error));
if (text->validator_name) utils->free(text->validator_name);
// if (text->oauth_validator) utils->free(text->oauth_validator);
if (text->propctx) utils->prop_dispose(&(text->propctx));
utils->free(text);
}
static sasl_server_plug_t oauth_server_plugins[] =
{
{
MECH_NAME, /* mech_name */
0, /* max_ssf */
SASL_SEC_NOPLAINTEXT
| SASL_SEC_NOANONYMOUS, /* security_flags */
SASL_FEAT_WANT_CLIENT_FIRST, /* features */
NULL, /* glob_context */
&oauth_server_mech_new, /* mech_new */
&oauth_server_mech_step, /* mech_step */
&oauth_server_mech_dispose, /* mech_dispose */
NULL, /* mech_free */
NULL, /* setpass */
NULL, /* user_query */
NULL, /* idle */
NULL, /* mech avail */
NULL /* spare */
}
};
/* printf("debug: %s %d \n", __FILE__, __LINE__); */
int oauth_server_plug_init(const sasl_utils_t *utils,
int maxversion,
int *out_version,
sasl_server_plug_t **pluglist,
int *plugcount)
{
if (maxversion < SASL_SERVER_PLUG_VERSION) {
SETERROR( utils, "OAUTH version mismatch");
return SASL_BADVERS;
}
*out_version = SASL_SERVER_PLUG_VERSION;
*pluglist = oauth_server_plugins;
*plugcount = 1;
return SASL_OK;
}
/************************ Client data structures ***************************/
/* Max auth header size is about 2k so 4k shoudl be enough */
#define MAX_OAUTH_CRSIZE 4096
#define CLIENT_CRED_CACHE "sasl_oauth_cache.json"
#define USER_RW_MODE (S_IRUSR|S_IWUSR)
typedef struct curl_data {
char *data;
int code;
int size;
int offset;
} curl_data_t;
typedef struct client_context {
char *out_buf;
unsigned out_buf_len;
char *username;
char *password;
char *refresh;
char *access;
char *auth_uri;
char *refresh_uri;
char *scope;
int access_expires;
int state;
char cr_buffer[MAX_OAUTH_CRSIZE+1];
char authhdr_buffer[MAX_OAUTH_CRSIZE+1];
curl_data_t curl;
int token_sent;
int ccache_fd;
FILE * ccache_file;
json_t *ccache_json;
int ccache_locked;
struct flock ccache_lockinfo;
} client_context_t;
/************************ Client worker functions***************************/
/*
** XXXXXXX Need to figure out a better name, also need to figure out
** portable paths. Probably involves reading $HOME or some such.
**
** ccache_* -- for maintaining the credential cache.
*/
/*
** ccache_lock
**
** Used for locking the store and as an IPC lock. Before entering
** the credential fetch phase of things and prompting the user for
** a password, lock so that things only get done once.
**
** XXXXXXX Need to work out ASYNC locking so we don't hang forever. It's
** too much work right now but it's needed.
*/
int ccache_lock (void *conn_context) {
client_context_t *text = (client_context_t *)conn_context;
if (1 > text->ccache_fd)
return SASL_FAIL;
switch (text->ccache_locked) {
case 0:
fcntl(text->ccache_fd, F_SETLKW, &text->ccache_lockinfo);
default:
text->ccache_locked++;
}
return SASL_OK;
}
/*
** ccache_unlock
**
** Used for unlocking the store and as an IPC unlock.
*/
int ccache_unlock (void *conn_context, int unlock_all) {
client_context_t *text = (client_context_t *)conn_context;
if (1 > text->ccache_fd)
return SASL_FAIL;
if (unlock_all && text->ccache_locked)
text->ccache_locked = 1;
switch (text->ccache_locked) {
case 0:
return SASL_OK;
break;
case 1:
fcntl(text->ccache_fd, F_UNLCK);
default:
text->ccache_locked--;
}
return SASL_OK;
}
/*
** ccache_init
**
** Set everything up for the ccache stuff.
*/
int ccache_init (void *conn_context) {
client_context_t *text = (client_context_t *)conn_context;
struct stat ccstat;
memset(&text->ccache_lockinfo, 0, sizeof(text->ccache_lockinfo));
text->ccache_lockinfo.l_type = F_WRLCK;
text->ccache_lockinfo.l_whence = SEEK_SET;
text->ccache_fd = open(CLIENT_CRED_CACHE, O_CREAT|O_RDWR|O_SYNC, USER_RW_MODE);
if (-1 == text->ccache_fd)
return SASL_FAIL;
if (-1 == fstat(text->ccache_fd, &ccstat)) goto fail;
if (USER_RW_MODE != ccstat.st_mode) {
if (-1 == fchmod(text->ccache_fd, USER_RW_MODE)) goto fail;
}
text->ccache_file = fdopen(text->ccache_fd, "r+");
return SASL_OK;
fail:
if (0 < text->ccache_fd) close(text->ccache_fd);
text->ccache_fd = -1;
return SASL_FAIL;
}
/*
** ccache_close
**
** an excess of completeness.
*/
void ccache_close (void *conn_context) {
client_context_t *text = (client_context_t *)conn_context;
if (NULL != text->ccache_file) {
fclose(text->ccache_file);
text->ccache_fd = 0;
}
if (text->ccache_json)
json_object_clear(text->ccache_json);
}
/*
** ccache_fetch
**
** Fetch the cached cred store if any.
*/
int ccache_fetch (void *conn_context,
sasl_client_params_t *params) {
client_context_t *text = (client_context_t *)conn_context;
json_error_t jerror;
json_t *jthis_host, *jtmp;
if (1 > text->ccache_fd)
return SASL_FAIL;
/*
** Note that the lock function has a counter, so it's safe to
** do a lock/unlock if we already have a lock set in an outer
** context. XXXXXXX I might be breaking all kinds of rules here.
*/
if (SASL_OK != ccache_lock(conn_context))
return SASL_FAIL;
if (text->ccache_json)
json_object_clear(text->ccache_json);
text->ccache_json = json_loadf(text->ccache_file, &jerror);
if (NULL == text->ccache_json) {
/*
** On fail, truncate what was in the file and provide an empty
** json object for use later.
*/
ftruncate(text->ccache_fd, 0);
text->ccache_json = json_object();
json_object_set(text->ccache_json,
"OAuth SASL Mechanism Version",
json_integer(MECH_VERSION));
} else {
/*
** What we do now is store a single cred per host.
**
** XXXXXXX We should eventually be more robust here. Users
** probably want to be able to do richer management of stored
** creds. OR it might want to be much simpler....
*/
jthis_host = json_object_get(text->ccache_json, params->serverFQDN);
if (jthis_host) {
/* we have cached data */
jtmp = json_object_get(jthis_host, JSON_TAG_USERNAME);
if (jtmp) {
text->username = strdup(json_string_value(jtmp));
}
jtmp = json_object_get(jthis_host, JSON_TAG_ACCESS);
if (jtmp) {
text->access = strdup(json_string_value(jtmp));
}
jtmp = json_object_get(jthis_host, JSON_TAG_REFRESH);
if (jtmp) {
text->refresh = strdup(json_string_value(jtmp));
}
jtmp = json_object_get(jthis_host, JSON_TAG_AUTH_URI);
if (jtmp) {
text->auth_uri = strdup(json_string_value(jtmp));
}
jtmp = json_object_get(jthis_host, JSON_TAG_REFRESH_URI);
if (jtmp) {
text->refresh_uri = strdup(json_string_value(jtmp));
}
jtmp = json_object_get(jthis_host, JSON_TAG_ACCESS_EXPIRES);
if (jtmp) {
text->access_expires = json_integer_value(jtmp);
}
}
}
/*
** Unlock backs off the lock we did at the top, only unlocks
** file if this was the only lock set.
*/
ccache_unlock(conn_context, 0);
return SASL_OK;
}
/*
** Write our current cred out to the store. Make sure
** to lock first. This is probably done when we have
** fetched a new cred or when we prompted for passwords
** so we don't know when we actually want to lock on
** the update itself. Fetch can lock and unlock.
*/
int ccache_update (void *conn_context,
sasl_client_params_t *params) {
client_context_t *text = (client_context_t *) conn_context;
json_t *jthis_host, *jtmp;
if (1 > text->ccache_fd)
return SASL_FAIL;
if (SASL_OK != ccache_fetch(text, params))
return SASL_FAIL;
/*
** What we do now is store a single cred per host.
**
** XXXXXXX We should eventually be more robust here. Users
** probably want to be able to do richer management of stored
** creds. OR it might want to be much simpler....
*/
jthis_host = json_object_get(text->ccache_json, params->serverFQDN);
if (!jthis_host) {
jthis_host = json_object();
if (NULL == jtmp)
return SASL_NOMEM;
if (-1 == json_object_set(text->ccache_json, params->serverFQDN, jthis_host))
return SASL_NOMEM;
}
/* we have cached data */
json_object_set(jthis_host, JSON_TAG_USERNAME,
json_string(text->username));
json_object_set(jthis_host, JSON_TAG_ACCESS,
json_string(text->access));
json_object_set(jthis_host, JSON_TAG_REFRESH,
json_string(text->refresh));
json_object_set(jthis_host, JSON_TAG_AUTH_URI,
json_string(text->auth_uri));
json_object_set(jthis_host, JSON_TAG_REFRESH_URI,
json_string(text->refresh_uri));
json_object_set(jthis_host, JSON_TAG_ACCESS_EXPIRES,
json_integer(text->access_expires));
/* now write it out */
if (-1 == json_dumpf(text->ccache_json, text->ccache_file, 0))
return SASL_FAIL;
return SASL_OK;
}
/***************************** Client Section *****************************/
static int oauth_client_mech_new(void *glob_context __attribute__((unused)),
sasl_client_params_t *params,
void **conn_context)
{
client_context_t *text;
/* holds state are in */
text = params->utils->malloc(sizeof(client_context_t));
if (text == NULL) {
MEMERROR( params->utils );
return SASL_NOMEM;
}
memset(text, 0, sizeof(client_context_t));
*conn_context = text;
ccache_init(text);
return SASL_OK;
}
/*
** oauth_client_curl_write_cb
**
** Catches the data read by CURL
**
** XXXXXXXX Note that we're assuming that we'll have Content-Length.
** This probably needs to be fixed.
*/
size_t oauth_client_curl_hdr_cb(void *buffer, size_t size,
size_t nmemb, void *userp) {
curl_data_t *curldata = userp;
int sizeN = size * nmemb;
char *buff = buffer;
if (0 == strncmp("HTTP/1.1 ", buff, 8)) {
if (curldata->data) {
free(curldata->data);
memset(curldata, 0, sizeof(curl_data_t));
}
curldata->code = atoi(buff+8);
}
if (0 == strncmp("Content-Length: ", buff, 16)) {
curldata->size = atoi(buff+16);
curldata->data = malloc(curldata->size +1);
if (NULL == curldata->data) return 0;
curldata->data[curldata->size] = 0;
}
return sizeN;
}
size_t oauth_client_curl_write_cb( void *ptr, size_t size, size_t nmemb, void *stream) {
curl_data_t *curldata = stream;
char *buff = ptr;
int sizeN = size * nmemb;
int cpsize=sizeN;
int freesize;
freesize = curldata->size - curldata->offset;
if (sizeN > freesize)
cpsize = freesize;
if (NULL == curldata->data || 0 == curldata->size) return 0;
if (curldata->offset < curldata->size) {
strncpy(curldata->data + curldata->offset, buff, cpsize);
curldata->offset += cpsize;
}
return sizeN;
}
/*
** We evidently have an expired access token, let's get a new one.
*/
int oauth_client_refresh_token(void *conn_context,
sasl_client_params_t *params,
const char *serverin,
unsigned serverinlen,
sasl_interact_t **prompt_need,
const char **clientout,
unsigned *clientoutlen,
sasl_out_params_t *oparams)
{
client_context_t *text = (client_context_t *) conn_context;
int result=SASL_OK;
char errbuff[ERRBUFFLEN + 1];
CURL *easyhandle = curl_easy_init();
// char data[2048];
// char *data="name=daniel&project=curl";
char *reqfmt = "grant_type=refresh-token&client_id=unreg:&client_secret=N/A&refresh_token=%s&format=json";
char *safe_refresh = curl_easy_escape(easyhandle, text->refresh, 0);
int bufflen = strlen(reqfmt)+1;
char *postbuffer;
json_t *jobj, *jtmp;
json_error_t jerror;
errbuff[ERRBUFFLEN] = 0;
bufflen += strlen(safe_refresh);
postbuffer = params->utils->malloc(bufflen);
if (!postbuffer)
return SASL_NOMEM;
sprintf(postbuffer, reqfmt, safe_refresh);
/* Set the form info */
curl_easy_setopt(easyhandle, CURLOPT_URL, text->auth_uri);
curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDS, postbuffer);
curl_easy_setopt(easyhandle, CURLOPT_POST, 1);
curl_easy_setopt(easyhandle, CURLOPT_HEADER, 0);
curl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, oauth_client_curl_hdr_cb);
curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, oauth_client_curl_write_cb);
curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &text->curl);
curl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &text->curl);
curl_easy_perform(easyhandle); /* post away! */
/*
** Find out if we succeeded. Failure means going back for
** a new username/password.
*/
switch (text->curl.code) {
case 401:
/* XXXXXXXX Should we send back to the password prompt here? Right
** now we're returning out.
*/
params->utils->free(text->username);
text->username = NULL;
text->state = CSTATE_NEW;
result = SASL_BADAUTH;
break;
case 200:
/* A 200 OK shoudl really have a JSON response in it... */
if (!text->curl.data) {
snprintf(errbuff, ERRBUFFLEN,
"Remote auth server returned %d but no text.", text->curl.code);
SETERROR( params->utils, errbuff);
return SASL_BADPROT;
}
jobj = json_loads(text->curl.data, &jerror);
if (!jobj) {
SETERROR( params->utils, "JSON parse failed.");
return SASL_BADPROT;
} else {
jtmp = json_object_get(jobj, "access_token");
if (jtmp) {
text->access = strdup(json_string_value(jtmp));
} else {
SETERROR( params->utils, "No access token returned.");
return SASL_BADPROT;
}
/* returned scope is optional */
jtmp = json_object_get(jobj, "scope");
if (jtmp) {
if (text->scope)
params->utils->free(text->scope);
text->scope = strdup(json_string_value(jtmp));
}
/* returned expires is optional */
jtmp = json_object_get(jobj, "expires");
if (jtmp) {
text->access_expires = time(NULL) + json_integer_value(jtmp) - 1;
}
json_object_clear(jobj);
}
break;
default:
snprintf(errbuff, ERRBUFFLEN,
"Remote auth server returns HTTP code %d", text->curl.code);
SETERROR( params->utils, errbuff);
return SASL_UNAVAIL;
}
return result;
}
/*
**
** know the access token is expired we'll refresh it if we can.
*/
int oauth_client_get_access(void *conn_context,
sasl_client_params_t *params,
const char *serverin,
unsigned serverinlen,
sasl_interact_t **prompt_need,
const char **clientout,
unsigned *clientoutlen,
sasl_out_params_t *oparams)
{
client_context_t *text = (client_context_t *) conn_context;
int result=SASL_OK;
char errbuff[ERRBUFFLEN + 1];
CURL *easyhandle = curl_easy_init();
char *reqfmt = "grant_type=basic-credentials&client_id=unreg:&client_secret=N/A&user=%s&password=%s&scope=%s&format=json";
char *safe_user = curl_easy_escape(easyhandle, text->username, 0);
char *safe_password = curl_easy_escape(easyhandle, text->password, 0);
char *safe_scope = NULL;
int bufflen = strlen(reqfmt)+1;
char *postbuffer;
json_t *jobj, *jtmp;
json_error_t jerror;
errbuff[ERRBUFFLEN] = 0;
bufflen += strlen(safe_user) + strlen(safe_password);
if (text->scope) {
safe_scope = curl_easy_escape(easyhandle, text->scope, 0);
bufflen += strlen(safe_scope);
} else {
safe_scope = "";
}
postbuffer = params->utils->malloc(bufflen);
if (!postbuffer)
return SASL_NOMEM;
sprintf(postbuffer, reqfmt, safe_user, safe_password, safe_scope);
/* Set the form info */
curl_easy_setopt(easyhandle, CURLOPT_URL, text->auth_uri);
curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDS, postbuffer);
curl_easy_setopt(easyhandle, CURLOPT_POST, 1);
curl_easy_setopt(easyhandle, CURLOPT_HEADER, 0);
curl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, oauth_client_curl_hdr_cb);
curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, oauth_client_curl_write_cb);
curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &text->curl);
curl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &text->curl);
curl_easy_perform(easyhandle); /* post away! */
/* once we have an token we don't want the password anymore */
params->utils->free(postbuffer);
if (text->password) {
memset(text->password, 0, strlen(text->password));
params->utils->free(text->password);
text->password = NULL;
}
/*
** Find out if we succeeded. Failure means going back for
** a new username/password.
*/
switch (text->curl.code) {
case 401:
/* XXXXXXXX Should we send back to the password prompt here? Right
** now we're returning out.
*/
params->utils->free(text->username);
text->username = NULL;
text->state = CSTATE_NEW;
result = SASL_BADAUTH;
break;
case 200:
/* A 200 OK shoudl really have a JSON response in it... */
if (!text->curl.data) {
snprintf(errbuff, ERRBUFFLEN,
"Remote auth server returned %d but no text.", text->curl.code);
SETERROR( params->utils, errbuff);
return SASL_BADPROT;
}