summaryrefslogtreecommitdiffstats
path: root/src/lib/krb5/krb/preauth_otp.c
blob: d343683c029cc795e27c0d6be25c6990480f03a9 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* lib/krb5/krb/preauth_otp.c - OTP clpreauth module */
/*
 * Copyright 2011 NORDUnet A/S.  All rights reserved.
 * Copyright 2011 Red Hat, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in
 *       the documentation and/or other materials provided with the
 *       distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "k5-int.h"
#include "k5-json.h"
#include "int-proto.h"

#include <krb5/clpreauth_plugin.h>
#include <ctype.h>

static krb5_preauthtype otp_client_supported_pa_types[] =
    { KRB5_PADATA_OTP_CHALLENGE, 0 };

/* Frees a tokeninfo. */
static void
free_tokeninfo(krb5_responder_otp_tokeninfo *ti)
{
    if (ti == NULL)
        return;

    free(ti->alg_id);
    free(ti->challenge);
    free(ti->token_id);
    free(ti->vendor);
    free(ti);
}

/* Converts a property of a json object into a char*. */
static krb5_error_code
codec_value_to_string(k5_json_object obj, const char *key, char **string)
{
    k5_json_value val;
    char *str;

    val = k5_json_object_get(obj, key);
    if (val == NULL)
        return ENOENT;

    if (k5_json_get_tid(val) != K5_JSON_TID_STRING)
        return EINVAL;

    str = strdup(k5_json_string_utf8(val));
    if (str == NULL)
        return ENOMEM;

    *string = str;
    return 0;
}

/* Converts a property of a json object into a krb5_data struct. */
static krb5_error_code
codec_value_to_data(k5_json_object obj, const char *key, krb5_data *data)
{
    krb5_error_code retval;
    char *tmp;

    retval = codec_value_to_string(obj, key, &tmp);
    if (retval != 0)
        return retval;

    *data = string2data(tmp);
    return 0;
}

/* Converts a krb5_data struct into a property of a JSON object. */
static krb5_error_code
codec_data_to_value(krb5_data *data, k5_json_object obj, const char *key)
{
    krb5_error_code retval;
    k5_json_string str;

    if (data->data == NULL)
        return 0;

    retval = k5_json_string_create_len(data->data, data->length, &str);
    if (retval)
        return retval;

    retval = k5_json_object_set(obj, key, str);
    k5_json_release(str);
    return retval;
}

/* Converts a property of a json object into a krb5_int32. */
static krb5_error_code
codec_value_to_int32(k5_json_object obj, const char *key, krb5_int32 *int32)
{
    k5_json_value val;

    val = k5_json_object_get(obj, key);
    if (val == NULL)
        return ENOENT;

    if (k5_json_get_tid(val) != K5_JSON_TID_NUMBER)
        return EINVAL;

    *int32 = k5_json_number_value(val);
    return 0;
}

/* Converts a krb5_int32 into a property of a JSON object. */
static krb5_error_code
codec_int32_to_value(krb5_int32 int32, k5_json_object obj, const char *key)
{
    krb5_error_code retval;
    k5_json_number num;

    if (int32 == -1)
        return 0;

    retval = k5_json_number_create(int32, &num);
    if (retval)
        return retval;

    retval = k5_json_object_set(obj, key, num);
    k5_json_release(num);
    return retval;
}

/* Converts a krb5_otp_tokeninfo into a JSON object. */
static krb5_error_code
codec_encode_tokeninfo(krb5_otp_tokeninfo *ti, k5_json_object *out)
{
    krb5_error_code retval;
    k5_json_object obj;
    krb5_flags flags;

    retval = k5_json_object_create(&obj);
    if (retval != 0)
        goto error;

    flags = KRB5_RESPONDER_OTP_FLAGS_COLLECT_TOKEN;
    if (ti->flags & KRB5_OTP_FLAG_COLLECT_PIN) {
        flags |= KRB5_RESPONDER_OTP_FLAGS_COLLECT_PIN;
        if (ti->flags & KRB5_OTP_FLAG_SEPARATE_PIN)
            flags |= KRB5_RESPONDER_OTP_FLAGS_NEXTOTP;
    }
    if (ti->flags & KRB5_OTP_FLAG_NEXTOTP)
        flags |= KRB5_RESPONDER_OTP_FLAGS_NEXTOTP;

    retval = codec_int32_to_value(flags, obj, "flags");
    if (retval != 0)
        goto error;

    retval = codec_data_to_value(&ti->vendor, obj, "vendor");
    if (retval != 0)
        goto error;

    retval = codec_data_to_value(&ti->challenge, obj, "challenge");
    if (retval != 0)
        goto error;

    retval = codec_int32_to_value(ti->length, obj, "length");
    if (retval != 0)
        goto error;

    if (ti->format != KRB5_OTP_FORMAT_BASE64 &&
        ti->format != KRB5_OTP_FORMAT_BINARY) {
        retval = codec_int32_to_value(ti->format, obj, "format");
        if (retval != 0)
            goto error;
    }

    retval = codec_data_to_value(&ti->token_id, obj, "tokenID");
    if (retval != 0)
        goto error;

    retval = codec_data_to_value(&ti->alg_id, obj, "algID");
    if (retval != 0)
        goto error;

    *out = obj;
    return 0;

error:
    k5_json_release(obj);
    return retval;
}

/* Converts a krb5_pa_otp_challenge into a JSON object. */
static krb5_error_code
codec_encode_challenge(krb5_context ctx, krb5_pa_otp_challenge *chl,
                       char **json)
{
    k5_json_object obj = NULL, tmp = NULL;
    k5_json_string str = NULL;
    k5_json_array arr = NULL;
    krb5_error_code retval;
    int i;

    retval = k5_json_object_create(&obj);
    if (retval != 0)
        goto cleanup;

    if (chl->service.data) {
        retval = k5_json_string_create_len(chl->service.data,
                                           chl->service.length, &str);
        if (retval != 0)
            goto cleanup;
        retval = k5_json_object_set(obj, "service", str);
        k5_json_release(str);
        if (retval != 0)
            goto cleanup;
    }

    retval = k5_json_array_create(&arr);
    if (retval != 0)
        goto cleanup;

    for (i = 0; chl->tokeninfo[i] != NULL ; i++) {
        retval = codec_encode_tokeninfo(chl->tokeninfo[i], &tmp);
        if (retval != 0)
            goto cleanup;

        retval = k5_json_array_add(arr, tmp);
        k5_json_release(tmp);
        if (retval != 0)
            goto cleanup;
    }

    retval = k5_json_object_set(obj, "tokenInfo", arr);
    if (retval != 0)
        goto cleanup;

    retval = k5_json_encode(obj, json);
    if (retval)
        goto cleanup;

cleanup:
    k5_json_release(arr);
    k5_json_release(obj);
    return retval;
}

/* Converts a JSON object into a krb5_responder_otp_tokeninfo. */
static krb5_responder_otp_tokeninfo *
codec_decode_tokeninfo(k5_json_object obj)
{
    krb5_responder_otp_tokeninfo *ti = NULL;
    krb5_error_code retval;

    ti = calloc(1, sizeof(krb5_responder_otp_tokeninfo));
    if (ti == NULL)
        goto error;

    retval = codec_value_to_int32(obj, "flags", &ti->flags);
    if (retval != 0)
        goto error;

    retval = codec_value_to_string(obj, "vendor", &ti->vendor);
    if (retval != 0 && retval != ENOENT)
        goto error;

    retval = codec_value_to_string(obj, "challenge", &ti->challenge);
    if (retval != 0 && retval != ENOENT)
        goto error;

    retval = codec_value_to_int32(obj, "length", &ti->length);
    if (retval == ENOENT)
        ti->length = -1;
    else if (retval != 0)
        goto error;

    retval = codec_value_to_int32(obj, "format", &ti->format);
    if (retval == ENOENT)
        ti->format = -1;
    else if (retval != 0)
        goto error;

    retval = codec_value_to_string(obj, "tokenID", &ti->token_id);
    if (retval != 0 && retval != ENOENT)
        goto error;

    retval = codec_value_to_string(obj, "algID", &ti->alg_id);
    if (retval != 0 && retval != ENOENT)
        goto error;

    return ti;

error:
    free_tokeninfo(ti);
    return NULL;
}

/* Converts a JSON object into a krb5_responder_otp_challenge. */
static krb5_responder_otp_challenge *
codec_decode_challenge(krb5_context ctx, const char *json)
{
    krb5_responder_otp_challenge *chl = NULL;
    k5_json_value obj = NULL, arr = NULL, tmp = NULL;
    krb5_error_code retval;
    size_t i;

    retval = k5_json_decode(json, &obj);
    if (retval != 0)
        goto error;

    if (k5_json_get_tid(obj) != K5_JSON_TID_OBJECT)
        goto error;

    arr = k5_json_object_get(obj, "tokenInfo");
    if (arr == NULL)
        goto error;

    if (k5_json_get_tid(arr) != K5_JSON_TID_ARRAY)
        goto error;

    chl = calloc(1, sizeof(krb5_responder_otp_challenge));
    if (chl == NULL)
        goto error;

    chl->tokeninfo = calloc(k5_json_array_length(arr) + 1,
                            sizeof(krb5_responder_otp_tokeninfo*));
    if (chl->tokeninfo == NULL)
        goto error;

    retval = codec_value_to_string(obj, "service", &chl->service);
    if (retval != 0 && retval != ENOENT)
        goto error;

    for (i = 0; i < k5_json_array_length(arr); i++) {
        tmp = k5_json_array_get(arr, i);
        if (k5_json_get_tid(tmp) != K5_JSON_TID_OBJECT)
            goto error;

        chl->tokeninfo[i] = codec_decode_tokeninfo(tmp);
        if (chl->tokeninfo[i] == NULL)
            goto error;
    }

    k5_json_release(obj);
    return chl;

error:
    if (chl != NULL) {
        for (i = 0; chl->tokeninfo != NULL && chl->tokeninfo[i] != NULL; i++)
            free_tokeninfo(chl->tokeninfo[i]);
        free(chl->tokeninfo);
        free(chl);
    }
    k5_json_release(obj);
    return NULL;
}

/* Decode the responder answer into a tokeninfo, a value and a pin. */
static krb5_error_code
codec_decode_answer(krb5_context context, const char *answer,
                    krb5_otp_tokeninfo **tis, krb5_otp_tokeninfo **ti,
                    krb5_data *value, krb5_data *pin)
{
    krb5_error_code retval;
    k5_json_value val = NULL;
    krb5_int32 indx, i;
    krb5_data tmp;

    if (answer == NULL)
        return EBADMSG;

    retval = k5_json_decode(answer, &val);
    if (retval != 0)
        goto cleanup;

    if (k5_json_get_tid(val) != K5_JSON_TID_OBJECT)
        goto cleanup;

    retval = codec_value_to_int32(val, "tokeninfo", &indx);
    if (retval != 0)
        goto cleanup;

    for (i = 0; tis[i] != NULL; i++) {
        if (i == indx) {
            retval = codec_value_to_data(val, "value", &tmp);
            if (retval != 0 && retval != ENOENT)
                goto cleanup;

            retval = codec_value_to_data(val, "pin", pin);
            if (retval != 0 && retval != ENOENT) {
                krb5_free_data_contents(context, &tmp);
                goto cleanup;
            }

            *value = tmp;
            *ti = tis[i];
            retval = 0;
            goto cleanup;
        }
    }
    retval = EINVAL;

cleanup:
    k5_json_release(val);
    return retval;
}

/* Takes the nonce from the challenge and encrypts it into the request. */
static krb5_error_code
encrypt_nonce(krb5_context ctx, krb5_keyblock *key,
              const krb5_pa_otp_challenge *chl, krb5_pa_otp_req *req)
{
    krb5_error_code retval;
    krb5_enc_data encdata;
    krb5_data *er;

    /* Encode the nonce. */
    retval = encode_krb5_pa_otp_enc_req(&chl->nonce, &er);
    if (retval != 0)
        return retval;

    /* Do the encryption. */
    retval = krb5_encrypt_helper(ctx, key, KRB5_KEYUSAGE_PA_OTP_REQUEST,
                                 er, &encdata);
    krb5_free_data(ctx, er);
    if (retval != 0)
        return retval;

    req->enc_data = encdata;
    return 0;
}

/* Checks to see if the user-supplied otp value matches the length and format
 * of the supplied tokeninfo. */
static int
otpvalue_matches_tokeninfo(const char *otpvalue, krb5_otp_tokeninfo *ti)
{
    int (*table[])(int c) = { isdigit, isxdigit, isalnum };

    if (otpvalue == NULL || ti == NULL)
        return 0;

    if (ti->length >= 0 && strlen(otpvalue) != (size_t)ti->length)
        return 0;

    if (ti->format >= 0 && ti->format < 3) {
        while (*otpvalue) {
            if (!(*table[ti->format])((unsigned char)*otpvalue++))
                return 0;
        }
    }

    return 1;
}

/* Performs a prompt and saves the response in the out parameter. */
static krb5_error_code
doprompt(krb5_context context, krb5_prompter_fct prompter, void *prompter_data,
         const char *banner, const char *prompttxt, char *out, size_t len)
{
    krb5_prompt prompt;
    krb5_data prompt_reply;
    krb5_error_code retval;

    if (prompttxt == NULL || out == NULL)
        return EINVAL;

    memset(out, 0, len);

    prompt_reply = make_data(out, len);
    prompt.reply = &prompt_reply;
    prompt.prompt = (char *)prompttxt;
    prompt.hidden = 1;

    retval = (*prompter)(context, prompter_data, NULL, banner, 1, &prompt);
    if (retval != 0)
        return retval;

    return 0;
}

/* Forces the user to choose a single tokeninfo via prompting. */
static krb5_error_code
prompt_for_tokeninfo(krb5_context context, krb5_prompter_fct prompter,
                     void *prompter_data, krb5_otp_tokeninfo **tis,
                     krb5_otp_tokeninfo **out_ti)
{
    char *banner = NULL, *tmp, response[1024];
    krb5_otp_tokeninfo *ti = NULL;
    krb5_error_code retval = 0;
    int i = 0, j = 0;

    for (i = 0; tis[i] != NULL; i++) {
        if (asprintf(&tmp, "%s\t%d. %s %.*s\n",
                     banner ? banner :
                         _("Please choose from the following:\n"),
                     i + 1, _("Vendor:"), tis[i]->vendor.length,
                     tis[i]->vendor.data) < 0) {
            free(banner);
            return ENOMEM;
        }

        free(banner);
        banner = tmp;
    }

    do {
        retval = doprompt(context, prompter, prompter_data,
                          banner, _("Enter #"), response, sizeof(response));
        if (retval != 0) {
            free(banner);
            return retval;
        }

        errno = 0;
        j = strtol(response, NULL, 0);
        if (errno != 0) {
            free(banner);
            return errno;
        }
        if (j < 1 || j > i)
            continue;

        ti = tis[--j];
    } while (ti == NULL);

    free(banner);
    *out_ti = ti;
    return 0;
}

/* Builds a challenge string from the given tokeninfo. */
static krb5_error_code
make_challenge(const krb5_otp_tokeninfo *ti, char **challenge)
{
    if (challenge == NULL)
        return EINVAL;

    *challenge = NULL;

    if (ti == NULL || ti->challenge.data == NULL)
        return 0;

    if (asprintf(challenge, "%s %.*s\n",
                 _("OTP Challenge:"),
                 ti->challenge.length,
                 ti->challenge.data) < 0)
        return ENOMEM;

    return 0;
}

/* Determines if a pin is required. If it is, it will be prompted for. */
static inline krb5_error_code
collect_pin(krb5_context context, krb5_prompter_fct prompter,
            void *prompter_data, const krb5_otp_tokeninfo *ti,
            krb5_data *out_pin)
{
    krb5_error_code retval;
    char otppin[1024];
    krb5_flags collect;
    krb5_data pin;

    /* If no PIN will be collected, don't prompt. */
    collect = ti->flags & (KRB5_OTP_FLAG_COLLECT_PIN |
                           KRB5_OTP_FLAG_SEPARATE_PIN);
    if (collect == 0) {
        *out_pin = empty_data();
        return 0;
    }

    /* Collect the PIN. */
    retval = doprompt(context, prompter, prompter_data, NULL,
                      _("OTP Token PIN"), otppin, sizeof(otppin));
    if (retval != 0)
        return retval;

    /* Set the PIN. */
    pin = make_data(strdup(otppin), strlen(otppin));
    if (pin.data == NULL)
        return ENOMEM;

    *out_pin = pin;
    return 0;
}

/* Builds a request using the specified tokeninfo, value and pin. */
static krb5_error_code
make_request(krb5_context ctx, krb5_otp_tokeninfo *ti, const krb5_data *value,
             const krb5_data *pin, krb5_pa_otp_req **out_req)
{
    krb5_pa_otp_req *req = NULL;
    krb5_error_code retval = 0;

    if (ti == NULL)
        return 0;

    if (ti->format == KRB5_OTP_FORMAT_BASE64)
        return ENOTSUP;

    req = calloc(1, sizeof(krb5_pa_otp_req));
    if (req == NULL)
        return ENOMEM;

    req->flags = ti->flags & KRB5_OTP_FLAG_NEXTOTP;

    retval = krb5int_copy_data_contents(ctx, &ti->vendor, &req->vendor);
    if (retval != 0)
        goto error;

    req->format = ti->format;

    retval = krb5int_copy_data_contents(ctx, &ti->token_id, &req->token_id);
    if (retval != 0)
        goto error;

    retval = krb5int_copy_data_contents(ctx, &ti->alg_id, &req->alg_id);
    if (retval != 0)
        goto error;

    retval = krb5int_copy_data_contents(ctx, value, &req->otp_value);
    if (retval != 0)
        goto error;

    if (ti->flags & KRB5_OTP_FLAG_COLLECT_PIN) {
        if (ti->flags & KRB5_OTP_FLAG_SEPARATE_PIN) {
            if (pin == NULL || pin->data == NULL) {
                retval = EINVAL; /* No pin found! */
                goto error;
            }

            retval = krb5int_copy_data_contents(ctx, pin, &req->pin);
            if (retval != 0)
                goto error;
        } else if (pin != NULL && pin->data != NULL) {
            krb5_free_data_contents(ctx, &req->otp_value);
            retval = asprintf(&req->otp_value.data, "%.*s%.*s",
                              pin->length, pin->data,
                              value->length, value->data);
            if (retval < 0) {
                retval = ENOMEM;
                req->otp_value = empty_data();
                goto error;
            }
            req->otp_value.length = req->pin.length + req->otp_value.length;
        } /* Otherwise, the responder has already combined them. */
    }

    *out_req = req;
    return 0;

error:
    k5_free_pa_otp_req(ctx, req);
    return retval;
}

/*
 * Filters a set of tokeninfos given an otp value.  If the set is reduced to
 * a single tokeninfo, it will be set in out_ti.  Otherwise, a new shallow copy
 * will be allocated in out_filtered.
 */
static inline krb5_error_code
filter_tokeninfos(krb5_context context, const char *otpvalue,
                  krb5_otp_tokeninfo **tis,
                  krb5_otp_tokeninfo ***out_filtered,
                  krb5_otp_tokeninfo **out_ti)
{
    krb5_otp_tokeninfo **filtered;
    size_t i = 0, j = 0;

    while (tis[i] != NULL)
        i++;

    filtered = calloc(i + 1, sizeof(const krb5_otp_tokeninfo *));
    if (filtered == NULL)
        return ENOMEM;

    /* Make a list of tokeninfos that match the value. */
    for (i = 0, j = 0; tis[i] != NULL; i++) {
        if (otpvalue_matches_tokeninfo(otpvalue, tis[i]))
            filtered[j++] = tis[i];
    }

    /* It is an error if we have no matching tokeninfos. */
    if (filtered[0] == NULL) {
        free(filtered);
        krb5_set_error_message(context, KRB5_PREAUTH_FAILED,
                               _("OTP value doesn't match "
                                 "any token formats"));
        return KRB5_PREAUTH_FAILED; /* We have no supported tokeninfos. */
    }

    /* Otherwise, if we have just one tokeninfo, choose it. */
    if (filtered[1] == NULL) {
        *out_ti = filtered[0];
        *out_filtered = NULL;
        free(filtered);
        return 0;
    }

    /* Otherwise, we'll return the remaining list. */
    *out_ti = NULL;
    *out_filtered = filtered;
    return 0;
}

/* Outputs the selected tokeninfo and possibly a value and pin.
 * Prompting may occur. */
static krb5_error_code
prompt_for_token(krb5_context context, krb5_prompter_fct prompter,
                 void *prompter_data, krb5_otp_tokeninfo **tis,
                 krb5_otp_tokeninfo **out_ti, krb5_data *out_value,
                 krb5_data *out_pin)
{
    krb5_otp_tokeninfo **filtered = NULL;
    krb5_otp_tokeninfo *ti = NULL;
    krb5_error_code retval;
    int i, challengers = 0;
    char *challenge = NULL;
    char otpvalue[1024];
    krb5_data value, pin;

    memset(otpvalue, 0, sizeof(otpvalue));

    if (tis == NULL || tis[0] == NULL || out_ti == NULL)
        return EINVAL;

    /* Count how many challenges we have. */
    for (i = 0; tis[i] != NULL; i++) {
        if (tis[i]->challenge.data != NULL)
            challengers++;
    }

    /* If we have only one tokeninfo as input, choose it. */
    if (i == 1)
        ti = tis[0];

    /* Setup our challenge, if present. */
    if (challengers > 0) {
        /* If we have multiple tokeninfos still, choose now. */
        if (ti == NULL) {
            retval = prompt_for_tokeninfo(context, prompter, prompter_data,
                                          tis, &ti);
            if (retval != 0)
                return retval;
        }

        /* Create the challenge prompt. */
        retval = make_challenge(ti, &challenge);
        if (retval != 0)
            return retval;
    }

    /* Prompt for token value. */
    retval = doprompt(context, prompter, prompter_data, challenge,
                      _("Enter OTP Token Value"), otpvalue, sizeof(otpvalue));
    free(challenge);
    if (retval != 0)
        return retval;

    if (ti == NULL) {
        /* Filter out tokeninfos that don't match our token value. */
        retval = filter_tokeninfos(context, otpvalue, tis, &filtered, &ti);
        if (retval != 0)
            return retval;

        /* If we still don't have a single tokeninfo, choose now. */
        if (filtered != NULL) {
            retval = prompt_for_tokeninfo(context, prompter, prompter_data,
                                          filtered, &ti);
            free(filtered);
            if (retval != 0)
                return retval;
        }
    }

    assert(ti != NULL);

    /* Set the value. */
    value = make_data(strdup(otpvalue), strlen(otpvalue));
    if (value.data == NULL)
        return ENOMEM;

    /* Collect the PIN, if necessary. */
    retval = collect_pin(context, prompter, prompter_data, ti, &pin);
    if (retval != 0) {
        krb5_free_data_contents(context, &value);
        return retval;
    }

    *out_value = value;
    *out_pin = pin;
    *out_ti = ti;
    return 0;
}

/* Encode the OTP request into a krb5_pa_data buffer. */
static krb5_error_code
set_pa_data(const krb5_pa_otp_req *req, krb5_pa_data ***pa_data_out)
{
    krb5_pa_data **out = NULL;
    krb5_data *tmp;

    /* Allocate the preauth data array and one item. */
    out = calloc(2, sizeof(krb5_pa_data *));
    if (out == NULL)
        goto error;
    out[0] = calloc(1, sizeof(krb5_pa_data));
    out[1] = NULL;
    if (out[0] == NULL)
        goto error;

    /* Encode our request into the preauth data item. */
    memset(out[0], 0, sizeof(krb5_pa_data));
    out[0]->pa_type = KRB5_PADATA_OTP_REQUEST;
    if (encode_krb5_pa_otp_req(req, &tmp) != 0)
        goto error;
    out[0]->contents = (krb5_octet *)tmp->data;
    out[0]->length = tmp->length;

    *pa_data_out = out;
    return 0;

error:
    if (out != NULL) {
        free(out[0]);
        free(out);
    }
    return ENOMEM;
}

/* Tests krb5_data to see if it is printable. */
static krb5_boolean
is_printable_string(const krb5_data *data)
{
    unsigned int i;

    if (data == NULL)
        return FALSE;

    for (i = 0; i < data->length; i++) {
        if (!isprint((unsigned char)data->data[i]))
            return FALSE;
    }

    return TRUE;
}

/* Returns TRUE when the given tokeninfo contains the subset of features we
 * support. */
static krb5_boolean
is_tokeninfo_supported(krb5_otp_tokeninfo *ti)
{
    krb5_flags supported_flags = KRB5_OTP_FLAG_COLLECT_PIN |
                                 KRB5_OTP_FLAG_NO_COLLECT_PIN |
                                 KRB5_OTP_FLAG_SEPARATE_PIN;

    /* Flags we don't support... */
    if (ti->flags & ~supported_flags)
        return FALSE;

    /* We don't currently support hashing. */
    if (ti->supported_hash_alg != NULL || ti->iteration_count >= 0)
        return FALSE;

    /* Remove tokeninfos with invalid vendor strings. */
    if (!is_printable_string(&ti->vendor))
        return FALSE;

    /* Remove tokeninfos with non-printable challenges. */
    if (!is_printable_string(&ti->challenge))
        return FALSE;

    /* We don't currently support base64. */
    if (ti->format == KRB5_OTP_FORMAT_BASE64)
        return FALSE;

    return TRUE;
}

/* Removes unsupported tokeninfos. Returns an error if no tokeninfos remain. */
static krb5_error_code
filter_supported_tokeninfos(krb5_context context, krb5_otp_tokeninfo **tis)
{
    size_t i, j;

    /* Filter out any tokeninfos we don't support. */
    for (i = 0, j = 0; tis[i] != NULL; i++) {
        if (!is_tokeninfo_supported(tis[i]))
            k5_free_otp_tokeninfo(context, tis[i]);
        else
            tis[j++] = tis[i];
    }

    /* Terminate the array. */
    tis[j] = NULL;

    if (tis[0] != NULL)
        return 0;

    krb5_set_error_message(context, KRB5_PREAUTH_FAILED,
                           _("No supported tokens"));
    return KRB5_PREAUTH_FAILED; /* We have no supported tokeninfos. */
}

/*
 * Try to find tokeninfos which match configuration data recorded in the input
 * ccache, and if exactly one is found, drop the rest.
 */
static krb5_error_code
filter_config_tokeninfos(krb5_context context,
                         krb5_clpreauth_callbacks cb,
                         krb5_clpreauth_rock rock,
                         krb5_otp_tokeninfo **tis)
{
    krb5_otp_tokeninfo *match = NULL;
    size_t i, j;
    const char *vendor, *alg_id, *token_id;

    /* Pull up what we know about the token we want to use. */
    vendor = cb->get_cc_config(context, rock, "vendor");
    alg_id = cb->get_cc_config(context, rock, "algID");
    token_id = cb->get_cc_config(context, rock, "tokenID");

    /* Look for a single matching entry. */
    for (i = 0; tis[i] != NULL; i++) {
        if (vendor != NULL && tis[i]->vendor.length > 0 &&
            !data_eq_string(tis[i]->vendor, vendor))
            continue;
        if (alg_id != NULL && tis[i]->alg_id.length > 0 &&
            !data_eq_string(tis[i]->alg_id, alg_id))
            continue;
        if (token_id != NULL && tis[i]->token_id.length > 0 &&
            !data_eq_string(tis[i]->token_id, token_id))
            continue;
        /* Oh, we already had a matching entry. More than one -> no change. */
        if (match != NULL)
            return 0;
        match = tis[i];
    }

    /* No matching entry -> no change. */
    if (match == NULL)
        return 0;

    /* Prune out everything except the best match. */
    for (i = 0, j = 0; tis[i] != NULL; i++) {
        if (tis[i] != match)
            k5_free_otp_tokeninfo(context, tis[i]);
        else
            tis[j++] = tis[i];
    }
    tis[j] = NULL;

    return 0;
}

static void
otp_client_request_init(krb5_context context, krb5_clpreauth_moddata moddata,
                        krb5_clpreauth_modreq *modreq_out)
{
    *modreq_out = calloc(1, sizeof(krb5_pa_otp_challenge *));
}

static krb5_error_code
otp_client_prep_questions(krb5_context context, krb5_clpreauth_moddata moddata,
                          krb5_clpreauth_modreq modreq,
                          krb5_get_init_creds_opt *opt,
                          krb5_clpreauth_callbacks cb,
                          krb5_clpreauth_rock rock, krb5_kdc_req *request,
                          krb5_data *encoded_request_body,
                          krb5_data *encoded_previous_request,
                          krb5_pa_data *pa_data)
{
    krb5_pa_otp_challenge *chl;
    krb5_error_code retval;
    krb5_data tmp;
    char *json;

    if (modreq == NULL)
        return ENOMEM;

    /* Decode the challenge. */
    tmp = make_data(pa_data->contents, pa_data->length);
    retval = decode_krb5_pa_otp_challenge(&tmp,
                                          (krb5_pa_otp_challenge **)modreq);
    if (retval != 0)
        return retval;
    chl = *(krb5_pa_otp_challenge **)modreq;

    /* Remove unsupported tokeninfos. */
    retval = filter_supported_tokeninfos(context, chl->tokeninfo);
    if (retval != 0)
        return retval;

    /* Remove tokeninfos that don't match the recorded description, if that
     * results in there being only one that does. */
    retval = filter_config_tokeninfos(context, cb, rock, chl->tokeninfo);
    if (retval != 0)
        return retval;

    /* Make the JSON representation. */
    retval = codec_encode_challenge(context, chl, &json);
    if (retval != 0)
        return retval;

    /* Ask the question. */
    retval = cb->ask_responder_question(context, rock,
                                        KRB5_RESPONDER_QUESTION_OTP,
                                        json);
    free(json);
    return retval;
}

/*
 * Save the vendor, algID, and tokenID values for the selected token to the
 * out_ccache, so that later we can try to use them to select the right one
 * without having ot ask the user.
 */
static void
save_config_tokeninfo(krb5_context context,
                      krb5_clpreauth_callbacks cb,
                      krb5_clpreauth_rock rock,
                      krb5_otp_tokeninfo *ti)
{
    char *tmp;
    if (ti->vendor.length > 0 &&
        asprintf(&tmp, "%.*s", ti->vendor.length, ti->vendor.data) >= 0) {
        cb->set_cc_config(context, rock, "vendor", tmp);
        free(tmp);
    }
    if (ti->alg_id.length > 0 &&
        asprintf(&tmp, "%.*s", ti->alg_id.length, ti->alg_id.data) >= 0) {
        cb->set_cc_config(context, rock, "algID", tmp);
        free(tmp);
    }
    if (ti->token_id.length > 0 &&
        asprintf(&tmp, "%.*s", ti->token_id.length, ti->token_id.data) >= 0) {
        cb->set_cc_config(context, rock, "tokenID", tmp);
        free(tmp);
    }
}

static krb5_error_code
otp_client_process(krb5_context context, krb5_clpreauth_moddata moddata,
                   krb5_clpreauth_modreq modreq, krb5_get_init_creds_opt *opt,
                   krb5_clpreauth_callbacks cb, krb5_clpreauth_rock rock,
                   krb5_kdc_req *request, krb5_data *encoded_request_body,
                   krb5_data *encoded_previous_request, krb5_pa_data *pa_data,
                   krb5_prompter_fct prompter, void *prompter_data,
                   krb5_pa_data ***pa_data_out)
{
    krb5_pa_otp_challenge *chl = NULL;
    krb5_otp_tokeninfo *ti = NULL;
    krb5_keyblock *as_key = NULL;
    krb5_pa_otp_req *req = NULL;
    krb5_error_code retval = 0;
    krb5_data value, pin;
    const char *answer;

    if (modreq == NULL)
        return ENOMEM;
    chl = *(krb5_pa_otp_challenge **)modreq;

    *pa_data_out = NULL;

    /* Get FAST armor key. */
    as_key = cb->fast_armor(context, rock);
    if (as_key == NULL)
        return ENOENT;

    /* Use FAST armor key as response key. */
    retval = cb->set_as_key(context, rock, as_key);
    if (retval != 0)
        return retval;

    /* Attempt to get token selection from the responder. */
    pin = empty_data();
    value = empty_data();
    answer = cb->get_responder_answer(context, rock,
                                      KRB5_RESPONDER_QUESTION_OTP);
    retval = codec_decode_answer(context, answer, chl->tokeninfo, &ti, &value,
                                 &pin);
    if (retval != 0) {
        /* If the responder doesn't have a token selection,
         * we need to select the token via prompting. */
        retval = prompt_for_token(context, prompter, prompter_data,
                                  chl->tokeninfo, &ti, &value, &pin);
        if (retval != 0)
            goto error;
    }

    /* Make the request. */
    retval = make_request(context, ti, &value, &pin, &req);
    if (retval != 0)
        goto error;

    /* Save information about the token which was used. */
    save_config_tokeninfo(context, cb, rock, ti);

    /* Encrypt the challenge's nonce and set it in the request. */
    retval = encrypt_nonce(context, as_key, chl, req);
    if (retval != 0)
        goto error;

    /* Encode the request into the pa_data output. */
    retval = set_pa_data(req, pa_data_out);
error:
    krb5_free_data_contents(context, &value);
    krb5_free_data_contents(context, &pin);
    k5_free_pa_otp_req(context, req);
    return retval;
}

static void
otp_client_request_fini(krb5_context context, krb5_clpreauth_moddata moddata,
                        krb5_clpreauth_modreq modreq)
{
    if (modreq == NULL)
        return;

    k5_free_pa_otp_challenge(context, *(krb5_pa_otp_challenge **)modreq);
    free(modreq);
}

krb5_error_code
clpreauth_otp_initvt(krb5_context context, int maj_ver, int min_ver,
                     krb5_plugin_vtable vtable)
{
    krb5_clpreauth_vtable vt;

    if (maj_ver != 1)
        return KRB5_PLUGIN_VER_NOTSUPP;

    vt = (krb5_clpreauth_vtable)vtable;
    vt->name = "otp";
    vt->pa_type_list = otp_client_supported_pa_types;
    vt->request_init = otp_client_request_init;
    vt->prep_questions = otp_client_prep_questions;
    vt->process = otp_client_process;
    vt->request_fini = otp_client_request_fini;
    vt->gic_opts = NULL;

    return 0;
}

krb5_error_code KRB5_CALLCONV
krb5_responder_otp_get_challenge(krb5_context ctx,
                                 krb5_responder_context rctx,
                                 krb5_responder_otp_challenge **chl)
{
    const char *answer;
    krb5_responder_otp_challenge *challenge;

    answer = krb5_responder_get_challenge(ctx, rctx,
                                          KRB5_RESPONDER_QUESTION_OTP);
    if (answer == NULL) {
        *chl = NULL;
        return 0;
    }

    challenge = codec_decode_challenge(ctx, answer);
    if (challenge == NULL)
        return ENOMEM;

    *chl = challenge;
    return 0;
}

krb5_error_code KRB5_CALLCONV
krb5_responder_otp_set_answer(krb5_context ctx, krb5_responder_context rctx,
                              size_t ti, const char *value, const char *pin)
{
    krb5_error_code retval;
    k5_json_object obj = NULL;
    k5_json_number num;
    k5_json_string str;
    char *tmp;

    retval = k5_json_object_create(&obj);
    if (retval != 0)
        goto error;

    retval = k5_json_number_create(ti, &num);
    if (retval != 0)
        goto error;

    retval = k5_json_object_set(obj, "tokeninfo", num);
    k5_json_release(num);
    if (retval != 0)
        goto error;

    if (value != NULL) {
        retval = k5_json_string_create(value, &str);
        if (retval != 0)
            goto error;

        retval = k5_json_object_set(obj, "value", str);
        k5_json_release(str);
        if (retval != 0)
            goto error;
    }

    if (pin != NULL) {
        retval = k5_json_string_create(pin, &str);
        if (retval != 0)
            goto error;

        retval = k5_json_object_set(obj, "pin", str);
        k5_json_release(str);
        if (retval != 0)
            goto error;
    }

    retval = k5_json_encode(obj, &tmp);
    if (retval != 0)
        goto error;
    k5_json_release(obj);

    retval = krb5_responder_set_answer(ctx, rctx, KRB5_RESPONDER_QUESTION_OTP,
                                       tmp);
    free(tmp);
    return retval;

error:
    k5_json_release(obj);
    return retval;
}

void KRB5_CALLCONV
krb5_responder_otp_challenge_free(krb5_context ctx,
                                  krb5_responder_context rctx,
                                  krb5_responder_otp_challenge *chl)
{
    size_t i;

    if (chl == NULL)
        return;

    for (i = 0; chl->tokeninfo[i]; i++)
        free_tokeninfo(chl->tokeninfo[i]);
    free(chl->service);
    free(chl->tokeninfo);
    free(chl);
}