diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-15 17:36:47 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-15 17:36:47 +0000 |
commit | 0441d265f2bb9da249c7abf333f0f771fadb4ab5 (patch) | |
tree | 3f3789daa2f6db22da6e55e92bee0062a7d613fe /src/lib-oauth2 | |
parent | Initial commit. (diff) | |
download | dovecot-0441d265f2bb9da249c7abf333f0f771fadb4ab5.tar.xz dovecot-0441d265f2bb9da249c7abf333f0f771fadb4ab5.zip |
Adding upstream version 1:2.3.21+dfsg1.upstream/1%2.3.21+dfsg1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/lib-oauth2')
-rw-r--r-- | src/lib-oauth2/Makefile.am | 71 | ||||
-rw-r--r-- | src/lib-oauth2/Makefile.in | 919 | ||||
-rw-r--r-- | src/lib-oauth2/oauth2-jwt.c | 525 | ||||
-rw-r--r-- | src/lib-oauth2/oauth2-key-cache.c | 158 | ||||
-rw-r--r-- | src/lib-oauth2/oauth2-private.h | 50 | ||||
-rw-r--r-- | src/lib-oauth2/oauth2-request.c | 377 | ||||
-rw-r--r-- | src/lib-oauth2/oauth2.c | 41 | ||||
-rw-r--r-- | src/lib-oauth2/oauth2.h | 149 | ||||
-rw-r--r-- | src/lib-oauth2/test-oauth2-json.c | 104 | ||||
-rw-r--r-- | src/lib-oauth2/test-oauth2-jwt.c | 919 |
10 files changed, 3313 insertions, 0 deletions
diff --git a/src/lib-oauth2/Makefile.am b/src/lib-oauth2/Makefile.am new file mode 100644 index 0000000..458b612 --- /dev/null +++ b/src/lib-oauth2/Makefile.am @@ -0,0 +1,71 @@ +AM_CPPFLAGS = \ + -I$(top_srcdir)/src/lib \ + -I$(top_srcdir)/src/lib-test \ + -I$(top_srcdir)/src/lib-http \ + -I$(top_srcdir)/src/lib-dcrypt \ + -I$(top_srcdir)/src/lib-dict \ + -I$(top_srcdir)/src/lib-settings + +noinst_LTLIBRARIES=liboauth2.la + +pkginc_libdir=$(pkgincludedir) +pkginc_lib_HEADERS = \ + oauth2.h + +noinst_HEADERS = \ + oauth2-private.h + +liboauth2_la_SOURCES = \ + oauth2.c \ + oauth2-request.c \ + oauth2-jwt.c \ + oauth2-key-cache.c + +test_programs = \ + test-oauth2-json \ + test-oauth2-jwt + +noinst_PROGRAMS = $(test_programs) + +test_libs = \ + $(noinst_LTLIBRARIES) \ + ../lib-dcrypt/libdcrypt.la \ + ../lib-http/libhttp.la \ + ../lib-dns/libdns.la \ + ../lib-ssl-iostream/libssl_iostream.la \ + ../lib-master/libmaster.la \ + ../lib-auth/libauth.la \ + ../lib-dict/libdict.la \ + ../lib-settings/libsettings.la \ + ../lib-test/libtest.la \ + ../lib/liblib.la \ + $(MODULE_LIBS) +test_deps = \ + $(noinst_LTLIBRARIES) \ + ../lib-dcrypt/libdcrypt.la \ + ../lib-http/libhttp.la \ + ../lib-dns/libdns.la \ + ../lib-ssl-iostream/libssl_iostream.la \ + ../lib-master/libmaster.la \ + ../lib-auth/libauth.la \ + ../lib-dict/libdict.la \ + ../lib-settings/libsettings.la \ + ../lib-test/libtest.la \ + ../lib/liblib.la + +test_oauth2_json_SOURCES = test-oauth2-json.c +test_oauth2_json_LDADD = $(test_libs) +test_oauth2_json_DEPENDENCIES = $(test_deps) + +test_oauth2_jwt_SOURCES = test-oauth2-jwt.c +test_oauth2_jwt_LDADD = $(test_libs) +if HAVE_WHOLE_ARCHIVE +test_oauth2_jwt_LDFLAGS = -Wl,$(LD_WHOLE_ARCHIVE),../lib-ssl-iostream/.libs/libssl_iostream.a,$(LD_NO_WHOLE_ARCHIVE) +endif +test_oauth2_jwt_DEPENDENCIES = $(test_deps) + +check-local: + for bin in $(test_programs); do \ + if ! $(RUN_TEST) ./$$bin; then exit 1; fi; \ + done + diff --git a/src/lib-oauth2/Makefile.in b/src/lib-oauth2/Makefile.in new file mode 100644 index 0000000..20fe218 --- /dev/null +++ b/src/lib-oauth2/Makefile.in @@ -0,0 +1,919 @@ +# Makefile.in generated by automake 1.16.3 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994-2020 Free Software Foundation, Inc. + +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + + + +VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +noinst_PROGRAMS = $(am__EXEEXT_1) +subdir = src/lib-oauth2 +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4/ac_checktype2.m4 \ + $(top_srcdir)/m4/ac_typeof.m4 $(top_srcdir)/m4/arc4random.m4 \ + $(top_srcdir)/m4/blockdev.m4 $(top_srcdir)/m4/c99_vsnprintf.m4 \ + $(top_srcdir)/m4/clock_gettime.m4 $(top_srcdir)/m4/crypt.m4 \ + $(top_srcdir)/m4/crypt_xpg6.m4 $(top_srcdir)/m4/dbqlk.m4 \ + $(top_srcdir)/m4/dirent_dtype.m4 $(top_srcdir)/m4/dovecot.m4 \ + $(top_srcdir)/m4/fd_passing.m4 $(top_srcdir)/m4/fdatasync.m4 \ + $(top_srcdir)/m4/flexible_array_member.m4 \ + $(top_srcdir)/m4/glibc.m4 $(top_srcdir)/m4/gmtime_max.m4 \ + $(top_srcdir)/m4/gmtime_tm_gmtoff.m4 \ + $(top_srcdir)/m4/ioloop.m4 $(top_srcdir)/m4/iovec.m4 \ + $(top_srcdir)/m4/ipv6.m4 $(top_srcdir)/m4/libcap.m4 \ + $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/libwrap.m4 \ + $(top_srcdir)/m4/linux_mremap.m4 $(top_srcdir)/m4/ltoptions.m4 \ + $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ + $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/mmap_write.m4 \ + $(top_srcdir)/m4/mntctl.m4 $(top_srcdir)/m4/modules.m4 \ + $(top_srcdir)/m4/notify.m4 $(top_srcdir)/m4/nsl.m4 \ + $(top_srcdir)/m4/off_t_max.m4 $(top_srcdir)/m4/pkg.m4 \ + $(top_srcdir)/m4/pr_set_dumpable.m4 \ + $(top_srcdir)/m4/q_quotactl.m4 $(top_srcdir)/m4/quota.m4 \ + $(top_srcdir)/m4/random.m4 $(top_srcdir)/m4/rlimit.m4 \ + $(top_srcdir)/m4/sendfile.m4 $(top_srcdir)/m4/size_t_signed.m4 \ + $(top_srcdir)/m4/sockpeercred.m4 $(top_srcdir)/m4/sql.m4 \ + $(top_srcdir)/m4/ssl.m4 $(top_srcdir)/m4/st_tim.m4 \ + $(top_srcdir)/m4/static_array.m4 $(top_srcdir)/m4/test_with.m4 \ + $(top_srcdir)/m4/time_t.m4 $(top_srcdir)/m4/typeof.m4 \ + $(top_srcdir)/m4/typeof_dev_t.m4 \ + $(top_srcdir)/m4/uoff_t_max.m4 $(top_srcdir)/m4/vararg.m4 \ + $(top_srcdir)/m4/want_apparmor.m4 \ + $(top_srcdir)/m4/want_bsdauth.m4 \ + $(top_srcdir)/m4/want_bzlib.m4 \ + $(top_srcdir)/m4/want_cassandra.m4 \ + $(top_srcdir)/m4/want_cdb.m4 \ + $(top_srcdir)/m4/want_checkpassword.m4 \ + $(top_srcdir)/m4/want_clucene.m4 $(top_srcdir)/m4/want_db.m4 \ + $(top_srcdir)/m4/want_gssapi.m4 $(top_srcdir)/m4/want_icu.m4 \ + $(top_srcdir)/m4/want_ldap.m4 $(top_srcdir)/m4/want_lua.m4 \ + $(top_srcdir)/m4/want_lz4.m4 $(top_srcdir)/m4/want_lzma.m4 \ + $(top_srcdir)/m4/want_mysql.m4 $(top_srcdir)/m4/want_pam.m4 \ + $(top_srcdir)/m4/want_passwd.m4 $(top_srcdir)/m4/want_pgsql.m4 \ + $(top_srcdir)/m4/want_prefetch.m4 \ + $(top_srcdir)/m4/want_shadow.m4 \ + $(top_srcdir)/m4/want_sodium.m4 $(top_srcdir)/m4/want_solr.m4 \ + $(top_srcdir)/m4/want_sqlite.m4 \ + $(top_srcdir)/m4/want_stemmer.m4 \ + $(top_srcdir)/m4/want_systemd.m4 \ + $(top_srcdir)/m4/want_textcat.m4 \ + $(top_srcdir)/m4/want_unwind.m4 $(top_srcdir)/m4/want_zlib.m4 \ + $(top_srcdir)/m4/want_zstd.m4 $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(noinst_HEADERS) \ + $(pkginc_lib_HEADERS) $(am__DIST_COMMON) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +am__EXEEXT_1 = test-oauth2-json$(EXEEXT) test-oauth2-jwt$(EXEEXT) +PROGRAMS = $(noinst_PROGRAMS) +LTLIBRARIES = $(noinst_LTLIBRARIES) +liboauth2_la_LIBADD = +am_liboauth2_la_OBJECTS = oauth2.lo oauth2-request.lo oauth2-jwt.lo \ + oauth2-key-cache.lo +liboauth2_la_OBJECTS = $(am_liboauth2_la_OBJECTS) +AM_V_lt = $(am__v_lt_@AM_V@) +am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) +am__v_lt_0 = --silent +am__v_lt_1 = +am_test_oauth2_json_OBJECTS = test-oauth2-json.$(OBJEXT) +test_oauth2_json_OBJECTS = $(am_test_oauth2_json_OBJECTS) +am__DEPENDENCIES_1 = +am__DEPENDENCIES_2 = $(noinst_LTLIBRARIES) ../lib-dcrypt/libdcrypt.la \ + ../lib-http/libhttp.la ../lib-dns/libdns.la \ + ../lib-ssl-iostream/libssl_iostream.la \ + ../lib-master/libmaster.la ../lib-auth/libauth.la \ + ../lib-dict/libdict.la ../lib-settings/libsettings.la \ + ../lib-test/libtest.la ../lib/liblib.la $(am__DEPENDENCIES_1) +am_test_oauth2_jwt_OBJECTS = test-oauth2-jwt.$(OBJEXT) +test_oauth2_jwt_OBJECTS = $(am_test_oauth2_jwt_OBJECTS) +test_oauth2_jwt_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ + $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ + $(AM_CFLAGS) $(CFLAGS) $(test_oauth2_jwt_LDFLAGS) $(LDFLAGS) \ + -o $@ +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/depcomp +am__maybe_remake_depfiles = depfiles +am__depfiles_remade = ./$(DEPDIR)/oauth2-jwt.Plo \ + ./$(DEPDIR)/oauth2-key-cache.Plo \ + ./$(DEPDIR)/oauth2-request.Plo ./$(DEPDIR)/oauth2.Plo \ + ./$(DEPDIR)/test-oauth2-json.Po ./$(DEPDIR)/test-oauth2-jwt.Po +am__mv = mv -f +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ + $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ + $(AM_CFLAGS) $(CFLAGS) +AM_V_CC = $(am__v_CC_@AM_V@) +am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) +am__v_CC_0 = @echo " CC " $@; +am__v_CC_1 = +CCLD = $(CC) +LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(AM_LDFLAGS) $(LDFLAGS) -o $@ +AM_V_CCLD = $(am__v_CCLD_@AM_V@) +am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) +am__v_CCLD_0 = @echo " CCLD " $@; +am__v_CCLD_1 = +SOURCES = $(liboauth2_la_SOURCES) $(test_oauth2_json_SOURCES) \ + $(test_oauth2_jwt_SOURCES) +DIST_SOURCES = $(liboauth2_la_SOURCES) $(test_oauth2_json_SOURCES) \ + $(test_oauth2_jwt_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(pkginc_libdir)" +HEADERS = $(noinst_HEADERS) $(pkginc_lib_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` +ETAGS = etags +CTAGS = ctags +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/depcomp +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +ACLOCAL_AMFLAGS = @ACLOCAL_AMFLAGS@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +APPARMOR_LIBS = @APPARMOR_LIBS@ +AR = @AR@ +AUTH_CFLAGS = @AUTH_CFLAGS@ +AUTH_LIBS = @AUTH_LIBS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +BINARY_CFLAGS = @BINARY_CFLAGS@ +BINARY_LDFLAGS = @BINARY_LDFLAGS@ +BISON = @BISON@ +CASSANDRA_CFLAGS = @CASSANDRA_CFLAGS@ +CASSANDRA_LIBS = @CASSANDRA_LIBS@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CDB_LIBS = @CDB_LIBS@ +CFLAGS = @CFLAGS@ +CLUCENE_CFLAGS = @CLUCENE_CFLAGS@ +CLUCENE_LIBS = @CLUCENE_LIBS@ +COMPRESS_LIBS = @COMPRESS_LIBS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CRYPT_LIBS = @CRYPT_LIBS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DICT_LIBS = @DICT_LIBS@ +DLLIB = @DLLIB@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +FLEX = @FLEX@ +FUZZER_CPPFLAGS = @FUZZER_CPPFLAGS@ +FUZZER_LDFLAGS = @FUZZER_LDFLAGS@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +KRB5CONFIG = @KRB5CONFIG@ +KRB5_CFLAGS = @KRB5_CFLAGS@ +KRB5_LIBS = @KRB5_LIBS@ +LD = @LD@ +LDAP_LIBS = @LDAP_LIBS@ +LDFLAGS = @LDFLAGS@ +LD_NO_WHOLE_ARCHIVE = @LD_NO_WHOLE_ARCHIVE@ +LD_WHOLE_ARCHIVE = @LD_WHOLE_ARCHIVE@ +LIBCAP = @LIBCAP@ +LIBDOVECOT = @LIBDOVECOT@ +LIBDOVECOT_COMPRESS = @LIBDOVECOT_COMPRESS@ +LIBDOVECOT_DEPS = @LIBDOVECOT_DEPS@ +LIBDOVECOT_DSYNC = @LIBDOVECOT_DSYNC@ +LIBDOVECOT_LA_LIBS = @LIBDOVECOT_LA_LIBS@ +LIBDOVECOT_LDA = @LIBDOVECOT_LDA@ +LIBDOVECOT_LDAP = @LIBDOVECOT_LDAP@ +LIBDOVECOT_LIBFTS = @LIBDOVECOT_LIBFTS@ +LIBDOVECOT_LIBFTS_DEPS = @LIBDOVECOT_LIBFTS_DEPS@ +LIBDOVECOT_LOGIN = @LIBDOVECOT_LOGIN@ +LIBDOVECOT_LUA = @LIBDOVECOT_LUA@ +LIBDOVECOT_LUA_DEPS = @LIBDOVECOT_LUA_DEPS@ +LIBDOVECOT_SQL = @LIBDOVECOT_SQL@ +LIBDOVECOT_STORAGE = @LIBDOVECOT_STORAGE@ +LIBDOVECOT_STORAGE_DEPS = @LIBDOVECOT_STORAGE_DEPS@ +LIBEXTTEXTCAT_CFLAGS = @LIBEXTTEXTCAT_CFLAGS@ +LIBEXTTEXTCAT_LIBS = @LIBEXTTEXTCAT_LIBS@ +LIBICONV = @LIBICONV@ +LIBICU_CFLAGS = @LIBICU_CFLAGS@ +LIBICU_LIBS = @LIBICU_LIBS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBSODIUM_CFLAGS = @LIBSODIUM_CFLAGS@ +LIBSODIUM_LIBS = @LIBSODIUM_LIBS@ +LIBTIRPC_CFLAGS = @LIBTIRPC_CFLAGS@ +LIBTIRPC_LIBS = @LIBTIRPC_LIBS@ +LIBTOOL = @LIBTOOL@ +LIBUNWIND_CFLAGS = @LIBUNWIND_CFLAGS@ +LIBUNWIND_LIBS = @LIBUNWIND_LIBS@ +LIBWRAP_LIBS = @LIBWRAP_LIBS@ +LINKED_STORAGE_LDADD = @LINKED_STORAGE_LDADD@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBICONV = @LTLIBICONV@ +LTLIBOBJS = @LTLIBOBJS@ +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ +LUA_CFLAGS = @LUA_CFLAGS@ +LUA_LIBS = @LUA_LIBS@ +MAINT = @MAINT@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MODULE_LIBS = @MODULE_LIBS@ +MODULE_SUFFIX = @MODULE_SUFFIX@ +MYSQL_CFLAGS = @MYSQL_CFLAGS@ +MYSQL_CONFIG = @MYSQL_CONFIG@ +MYSQL_LIBS = @MYSQL_LIBS@ +NM = @NM@ +NMEDIT = @NMEDIT@ +NOPLUGIN_LDFLAGS = @NOPLUGIN_LDFLAGS@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PANDOC = @PANDOC@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PGSQL_CFLAGS = @PGSQL_CFLAGS@ +PGSQL_LIBS = @PGSQL_LIBS@ +PG_CONFIG = @PG_CONFIG@ +PIE_CFLAGS = @PIE_CFLAGS@ +PIE_LDFLAGS = @PIE_LDFLAGS@ +PKG_CONFIG = @PKG_CONFIG@ +PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ +PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ +QUOTA_LIBS = @QUOTA_LIBS@ +RANLIB = @RANLIB@ +RELRO_LDFLAGS = @RELRO_LDFLAGS@ +RPCGEN = @RPCGEN@ +RUN_TEST = @RUN_TEST@ +SED = @SED@ +SETTING_FILES = @SETTING_FILES@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SQLITE_CFLAGS = @SQLITE_CFLAGS@ +SQLITE_LIBS = @SQLITE_LIBS@ +SQL_CFLAGS = @SQL_CFLAGS@ +SQL_LIBS = @SQL_LIBS@ +SSL_CFLAGS = @SSL_CFLAGS@ +SSL_LIBS = @SSL_LIBS@ +STRIP = @STRIP@ +SYSTEMD_CFLAGS = @SYSTEMD_CFLAGS@ +SYSTEMD_LIBS = @SYSTEMD_LIBS@ +VALGRIND = @VALGRIND@ +VERSION = @VERSION@ +ZSTD_CFLAGS = @ZSTD_CFLAGS@ +ZSTD_LIBS = @ZSTD_LIBS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +dict_drivers = @dict_drivers@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +moduledir = @moduledir@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +rundir = @rundir@ +runstatedir = @runstatedir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +sql_drivers = @sql_drivers@ +srcdir = @srcdir@ +ssldir = @ssldir@ +statedir = @statedir@ +sysconfdir = @sysconfdir@ +systemdservicetype = @systemdservicetype@ +systemdsystemunitdir = @systemdsystemunitdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +AM_CPPFLAGS = \ + -I$(top_srcdir)/src/lib \ + -I$(top_srcdir)/src/lib-test \ + -I$(top_srcdir)/src/lib-http \ + -I$(top_srcdir)/src/lib-dcrypt \ + -I$(top_srcdir)/src/lib-dict \ + -I$(top_srcdir)/src/lib-settings + +noinst_LTLIBRARIES = liboauth2.la +pkginc_libdir = $(pkgincludedir) +pkginc_lib_HEADERS = \ + oauth2.h + +noinst_HEADERS = \ + oauth2-private.h + +liboauth2_la_SOURCES = \ + oauth2.c \ + oauth2-request.c \ + oauth2-jwt.c \ + oauth2-key-cache.c + +test_programs = \ + test-oauth2-json \ + test-oauth2-jwt + +test_libs = \ + $(noinst_LTLIBRARIES) \ + ../lib-dcrypt/libdcrypt.la \ + ../lib-http/libhttp.la \ + ../lib-dns/libdns.la \ + ../lib-ssl-iostream/libssl_iostream.la \ + ../lib-master/libmaster.la \ + ../lib-auth/libauth.la \ + ../lib-dict/libdict.la \ + ../lib-settings/libsettings.la \ + ../lib-test/libtest.la \ + ../lib/liblib.la \ + $(MODULE_LIBS) + +test_deps = \ + $(noinst_LTLIBRARIES) \ + ../lib-dcrypt/libdcrypt.la \ + ../lib-http/libhttp.la \ + ../lib-dns/libdns.la \ + ../lib-ssl-iostream/libssl_iostream.la \ + ../lib-master/libmaster.la \ + ../lib-auth/libauth.la \ + ../lib-dict/libdict.la \ + ../lib-settings/libsettings.la \ + ../lib-test/libtest.la \ + ../lib/liblib.la + +test_oauth2_json_SOURCES = test-oauth2-json.c +test_oauth2_json_LDADD = $(test_libs) +test_oauth2_json_DEPENDENCIES = $(test_deps) +test_oauth2_jwt_SOURCES = test-oauth2-jwt.c +test_oauth2_jwt_LDADD = $(test_libs) +@HAVE_WHOLE_ARCHIVE_TRUE@test_oauth2_jwt_LDFLAGS = -Wl,$(LD_WHOLE_ARCHIVE),../lib-ssl-iostream/.libs/libssl_iostream.a,$(LD_NO_WHOLE_ARCHIVE) +test_oauth2_jwt_DEPENDENCIES = $(test_deps) +all: all-am + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib-oauth2/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/lib-oauth2/Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +clean-noinstPROGRAMS: + @list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \ + echo " rm -f" $$list; \ + rm -f $$list || exit $$?; \ + test -n "$(EXEEXT)" || exit 0; \ + list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ + echo " rm -f" $$list; \ + rm -f $$list + +clean-noinstLTLIBRARIES: + -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) + @list='$(noinst_LTLIBRARIES)'; \ + locs=`for p in $$list; do echo $$p; done | \ + sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ + sort -u`; \ + test -z "$$locs" || { \ + echo rm -f $${locs}; \ + rm -f $${locs}; \ + } + +liboauth2.la: $(liboauth2_la_OBJECTS) $(liboauth2_la_DEPENDENCIES) $(EXTRA_liboauth2_la_DEPENDENCIES) + $(AM_V_CCLD)$(LINK) $(liboauth2_la_OBJECTS) $(liboauth2_la_LIBADD) $(LIBS) + +test-oauth2-json$(EXEEXT): $(test_oauth2_json_OBJECTS) $(test_oauth2_json_DEPENDENCIES) $(EXTRA_test_oauth2_json_DEPENDENCIES) + @rm -f test-oauth2-json$(EXEEXT) + $(AM_V_CCLD)$(LINK) $(test_oauth2_json_OBJECTS) $(test_oauth2_json_LDADD) $(LIBS) + +test-oauth2-jwt$(EXEEXT): $(test_oauth2_jwt_OBJECTS) $(test_oauth2_jwt_DEPENDENCIES) $(EXTRA_test_oauth2_jwt_DEPENDENCIES) + @rm -f test-oauth2-jwt$(EXEEXT) + $(AM_V_CCLD)$(test_oauth2_jwt_LINK) $(test_oauth2_jwt_OBJECTS) $(test_oauth2_jwt_LDADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/oauth2-jwt.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/oauth2-key-cache.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/oauth2-request.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/oauth2.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test-oauth2-json.Po@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test-oauth2-jwt.Po@am__quote@ # am--include-marker + +$(am__depfiles_remade): + @$(MKDIR_P) $(@D) + @echo '# dummy' >$@-t && $(am__mv) $@-t $@ + +am--depfiles: $(am__depfiles_remade) + +.c.o: +@am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< + +.c.obj: +@am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` + +.c.lo: +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-pkginc_libHEADERS: $(pkginc_lib_HEADERS) + @$(NORMAL_INSTALL) + @list='$(pkginc_lib_HEADERS)'; test -n "$(pkginc_libdir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(pkginc_libdir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(pkginc_libdir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(pkginc_libdir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(pkginc_libdir)" || exit $$?; \ + done + +uninstall-pkginc_libHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(pkginc_lib_HEADERS)'; test -n "$(pkginc_libdir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(pkginc_libdir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ + here=`pwd`; \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(BUILT_SOURCES) + $(MAKE) $(AM_MAKEFLAGS) distdir-am + +distdir-am: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am + $(MAKE) $(AM_MAKEFLAGS) check-local +check: check-am +all-am: Makefile $(PROGRAMS) $(LTLIBRARIES) $(HEADERS) +installdirs: + for dir in "$(DESTDIR)$(pkginc_libdir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ + clean-noinstPROGRAMS mostlyclean-am + +distclean: distclean-am + -rm -f ./$(DEPDIR)/oauth2-jwt.Plo + -rm -f ./$(DEPDIR)/oauth2-key-cache.Plo + -rm -f ./$(DEPDIR)/oauth2-request.Plo + -rm -f ./$(DEPDIR)/oauth2.Plo + -rm -f ./$(DEPDIR)/test-oauth2-json.Po + -rm -f ./$(DEPDIR)/test-oauth2-jwt.Po + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-pkginc_libHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f ./$(DEPDIR)/oauth2-jwt.Plo + -rm -f ./$(DEPDIR)/oauth2-key-cache.Plo + -rm -f ./$(DEPDIR)/oauth2-request.Plo + -rm -f ./$(DEPDIR)/oauth2.Plo + -rm -f ./$(DEPDIR)/test-oauth2-json.Po + -rm -f ./$(DEPDIR)/test-oauth2-jwt.Po + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-pkginc_libHEADERS + +.MAKE: check-am install-am install-strip + +.PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am \ + check-local clean clean-generic clean-libtool \ + clean-noinstLTLIBRARIES clean-noinstPROGRAMS cscopelist-am \ + ctags ctags-am distclean distclean-compile distclean-generic \ + distclean-libtool distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-dvi install-dvi-am install-exec \ + install-exec-am install-html install-html-am install-info \ + install-info-am install-man install-pdf install-pdf-am \ + install-pkginc_libHEADERS install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ + pdf pdf-am ps ps-am tags tags-am uninstall uninstall-am \ + uninstall-pkginc_libHEADERS + +.PRECIOUS: Makefile + + +check-local: + for bin in $(test_programs); do \ + if ! $(RUN_TEST) ./$$bin; then exit 1; fi; \ + done + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/src/lib-oauth2/oauth2-jwt.c b/src/lib-oauth2/oauth2-jwt.c new file mode 100644 index 0000000..bc7779f --- /dev/null +++ b/src/lib-oauth2/oauth2-jwt.c @@ -0,0 +1,525 @@ +/* Copyright (c) 2020 Dovecot authors, see the included COPYING file */ + +#include "lib.h" +#include "buffer.h" +#include "str.h" +#include "hmac.h" +#include "array.h" +#include "hash-method.h" +#include "istream.h" +#include "iso8601-date.h" +#include "json-tree.h" +#include "array.h" +#include "base64.h" +#include "str-sanitize.h" +#include "dcrypt.h" +#include "var-expand.h" +#include "oauth2.h" +#include "oauth2-private.h" +#include "dict.h" + +#include <time.h> + +static const char *get_field(const struct json_tree *tree, const char *key) +{ + const struct json_tree_node *root = json_tree_root(tree); + const struct json_tree_node *value_node = json_tree_find_key(root, key); + if (value_node == NULL || value_node->value_type == JSON_TYPE_OBJECT || + value_node->value_type == JSON_TYPE_ARRAY) + return NULL; + return json_tree_get_value_str(value_node); +} + +static int get_time_field(const struct json_tree *tree, const char *key, + int64_t *value_r) +{ + time_t tvalue; + const char *value = get_field(tree, key); + int tz_offset ATTR_UNUSED; + if (value == NULL) + return 0; + if (str_to_int64(value, value_r) == 0) { + if (*value_r < 0) + return -1; + return 1; + } else if (iso8601_date_parse((const unsigned char*)value, strlen(value), + &tvalue, &tz_offset)) { + if (tvalue < 0) + return -1; + *value_r = tvalue; + return 1; + } + return -1; +} + +/* Escapes '/' and '%' in identifier to %hex */ +static const char *escape_identifier(const char *identifier) +{ + size_t pos = strcspn(identifier, "/%"); + /* nothing to escape */ + if (identifier[pos] == '\0') + return identifier; + + size_t len = strlen(identifier); + string_t *new_id = t_str_new(len); + str_append_data(new_id, identifier, pos); + + for (size_t i = pos; i < len; i++) { + switch (identifier[i]) { + case '/': + str_append(new_id, "%2f"); + break; + case '%': + str_append(new_id, "%25"); + break; + default: + str_append_c(new_id, identifier[i]); + break; + } + } + return str_c(new_id); +} + +static int +oauth2_lookup_hmac_key(const struct oauth2_settings *set, const char *azp, + const char *alg, const char *key_id, + const buffer_t **hmac_key_r, const char **error_r) +{ + const char *base64_key; + const char *cache_key_id, *lookup_key; + int ret; + + cache_key_id = t_strconcat(azp, ".", alg, ".", key_id, NULL); + if (oauth2_validation_key_cache_lookup_hmac_key( + set->key_cache, cache_key_id, hmac_key_r) == 0) + return 0; + + + /* do a synchronous dict lookup */ + lookup_key = t_strconcat(DICT_PATH_SHARED, azp, "/", alg, "/", key_id, + NULL); + struct dict_op_settings dict_set = { + .username = NULL, + }; + if ((ret = dict_lookup(set->key_dict, &dict_set, pool_datastack_create(), + lookup_key, &base64_key, error_r)) < 0) { + return -1; + } else if (ret == 0) { + *error_r = t_strdup_printf("%s key '%s' not found", + alg, key_id); + return -1; + } + + /* decode key */ + buffer_t *key = t_base64_decode_str(base64_key); + if (key->used == 0) { + *error_r = "Invalid base64 encoded key"; + return -1; + } + oauth2_validation_key_cache_insert_hmac_key(set->key_cache, + cache_key_id, key); + *hmac_key_r = key; + return 0; +} + +static int +oauth2_validate_hmac(const struct oauth2_settings *set, const char *azp, + const char *alg, const char *key_id, + const char *const *blobs, const char **error_r) +{ + const struct hash_method *method; + + if (strcmp(alg, "HS256") == 0) + method = hash_method_lookup("sha256"); + else if (strcmp(alg, "HS384") == 0) + method = hash_method_lookup("sha384"); + else if (strcmp(alg, "HS512") == 0) + method = hash_method_lookup("sha512"); + else { + *error_r = t_strdup_printf("unsupported algorithm '%s'", alg); + return -1; + } + + const buffer_t *key; + if (oauth2_lookup_hmac_key(set, azp, alg, key_id, &key, error_r) < 0) + return -1; + + struct hmac_context ctx; + hmac_init(&ctx, key->data, key->used, method); + hmac_update(&ctx, blobs[0], strlen(blobs[0])); + hmac_update(&ctx, ".", 1); + hmac_update(&ctx, blobs[1], strlen(blobs[1])); + unsigned char digest[method->digest_size]; + + hmac_final(&ctx, digest); + + buffer_t *their_digest = + t_base64url_decode_str(BASE64_DECODE_FLAG_NO_PADDING, blobs[2]); + if (method->digest_size != their_digest->used || + !mem_equals_timing_safe(digest, their_digest->data, + method->digest_size)) { + *error_r = "Incorrect JWT signature"; + return -1; + } + return 0; +} + +static int +oauth2_lookup_pubkey(const struct oauth2_settings *set, const char *azp, + const char *alg, const char *key_id, + struct dcrypt_public_key **key_r, const char **error_r) +{ + const char *key_str; + const char *cache_key_id, *lookup_key; + int ret; + + cache_key_id = t_strconcat(azp, ".", alg, ".", key_id, NULL); + if (oauth2_validation_key_cache_lookup_pubkey( + set->key_cache, cache_key_id, key_r) == 0) + return 0; + + /* do a synchronous dict lookup */ + lookup_key = t_strconcat(DICT_PATH_SHARED, azp, "/", alg, "/", key_id, + NULL); + struct dict_op_settings dict_set = { + .username = NULL, + }; + if ((ret = dict_lookup(set->key_dict, &dict_set, pool_datastack_create(), + lookup_key, &key_str, error_r)) < 0) { + return -1; + } else if (ret == 0) { + *error_r = t_strdup_printf("%s key '%s' not found", + alg, key_id); + return -1; + } + + /* try to load key */ + struct dcrypt_public_key *pubkey; + const char *error; + if (!dcrypt_key_load_public(&pubkey, key_str, &error)) { + *error_r = t_strdup_printf("Cannot load key: %s", error); + return -1; + } + + /* cache key */ + oauth2_validation_key_cache_insert_pubkey(set->key_cache, cache_key_id, + pubkey); + *key_r = pubkey; + return 0; +} + +static int +oauth2_validate_rsa_ecdsa(const struct oauth2_settings *set, + const char *azp, const char *alg, const char *key_id, + const char *const *blobs, const char **error_r) +{ + const char *method; + enum dcrypt_padding padding; + enum dcrypt_signature_format sig_format; + + if (!dcrypt_is_initialized()) { + *error_r = "No crypto library loaded"; + return -1; + } + + if (str_begins(alg, "RS")) { + padding = DCRYPT_PADDING_RSA_PKCS1; + sig_format = DCRYPT_SIGNATURE_FORMAT_DSS; + } else if (str_begins(alg, "PS")) { + padding = DCRYPT_PADDING_RSA_PKCS1_PSS; + sig_format = DCRYPT_SIGNATURE_FORMAT_DSS; + } else if (str_begins(alg, "ES")) { + padding = DCRYPT_PADDING_DEFAULT; + sig_format = DCRYPT_SIGNATURE_FORMAT_X962; + } else { + /* this should be checked by caller */ + i_unreached(); + } + + if (strcmp(alg+2, "256") == 0) { + method = "sha256"; + } else if (strcmp(alg+2, "384") == 0) { + method = "sha384"; + } else if (strcmp(alg+2, "512") == 0) { + method = "sha512"; + } else { + *error_r = t_strdup_printf("Unsupported algorithm '%s'", alg); + return -1; + } + + buffer_t *signature = + t_base64url_decode_str(BASE64_DECODE_FLAG_NO_PADDING, blobs[2]); + + struct dcrypt_public_key *pubkey; + if (oauth2_lookup_pubkey(set, azp, alg, key_id, &pubkey, error_r) < 0) + return -1; + + /* data to verify */ + const char *data = t_strconcat(blobs[0], ".", blobs[1], NULL); + + /* verify signature */ + bool valid; + if (!dcrypt_verify(pubkey, method, sig_format, data, strlen(data), + signature->data, signature->used, &valid, padding, + error_r)) { + valid = FALSE; + } else if (!valid) { + *error_r = "Bad signature"; + } + + return valid ? 0 : -1; +} + +static int +oauth2_validate_signature(const struct oauth2_settings *set, const char *azp, + const char *alg, const char *key_id, + const char *const *blobs, const char **error_r) +{ + if (str_begins(alg, "HS")) { + return oauth2_validate_hmac(set, azp, alg, key_id, blobs, + error_r); + } else if (str_begins(alg, "RS") || str_begins(alg, "PS") || + str_begins(alg, "ES")) { + return oauth2_validate_rsa_ecdsa(set, azp, alg, key_id, blobs, + error_r); + } + + *error_r = t_strdup_printf("Unsupported algorithm '%s'", alg); + return -1; +} + +static void +oauth2_jwt_copy_fields(ARRAY_TYPE(oauth2_field) *fields, struct json_tree *tree) +{ + pool_t pool = array_get_pool(fields); + ARRAY(const struct json_tree_node*) nodes; + const struct json_tree_node *root = json_tree_root(tree); + + t_array_init(&nodes, 1); + array_push_back(&nodes, &root); + + while (array_count(&nodes) > 0) { + const struct json_tree_node *const *pnode = array_front(&nodes); + const struct json_tree_node *node = *pnode; + array_pop_front(&nodes); + while (node != NULL) { + if (node->value_type == JSON_TYPE_OBJECT) { + root = node->value.child; + array_push_back(&nodes, &root); + } else if (node->key != NULL) { + struct oauth2_field *field = + array_append_space(fields); + field->name = p_strdup(pool, node->key); + field->value = p_strdup( + pool, json_tree_get_value_str(node)); + } + node = node->next; + } + } +} + +static int +oauth2_jwt_header_process(struct json_tree *tree, const char **alg_r, + const char **kid_r, const char **error_r) +{ + const char *alg = get_field(tree, "alg"); + const char *kid = get_field(tree, "kid"); + + if (alg == NULL) { + *error_r = "Cannot find 'alg' field"; + return -1; + } + + /* These are lost when tree is deinitialized. + Make sure algorithm is uppercased. */ + *alg_r = t_str_ucase(alg); + *kid_r = t_strdup(kid); + return 0; +} + +static bool check_scope(const char *req, const char *got) +{ + const char *const *scope_req = t_strsplit_spaces(req, " ,"); + const char *const *scope_got = t_strsplit_spaces(got, " ,"); + + for (; *scope_req != NULL; scope_req++) + if (!str_array_icase_find(scope_got, *scope_req)) + return FALSE; + return TRUE; +} + +static int +oauth2_jwt_body_process(const struct oauth2_settings *set, const char *alg, + const char *kid, ARRAY_TYPE(oauth2_field) *fields, + struct json_tree *tree, const char *const *blobs, + const char **error_r) +{ + const char *sub = get_field(tree, "sub"); + + int ret; + int64_t t0 = time(NULL); + /* default IAT and NBF to now */ + int64_t iat, nbf, exp; + int tz_offset ATTR_UNUSED; + + if (sub == NULL) { + *error_r = "Missing 'sub' field"; + return -1; + } + + if ((ret = get_time_field(tree, "exp", &exp)) < 1) { + *error_r = t_strdup_printf("%s 'exp' field", + ret == 0 ? "Missing" : "Malformed"); + return -1; + } + + if ((ret = get_time_field(tree, "nbf", &nbf)) < 0) { + *error_r = "Malformed 'nbf' field"; + return -1; + } else if (ret == 0 || nbf == 0) + nbf = t0; + + if ((ret = get_time_field(tree, "iat", &iat)) < 0) { + *error_r = "Malformed 'iat' field"; + return -1; + } else if (ret == 0 || iat == 0) + iat = t0; + + if (nbf > t0) { + *error_r = "Token is not valid yet"; + return -1; + } + if (iat > t0) { + *error_r = "Token is issued in future"; + return -1; + } + if (exp < t0) { + *error_r = "Token has expired"; + return -1; + } + + /* ensure token dates are not conflicting */ + if (exp < iat || + exp < nbf) { + *error_r = "Token time values are conflicting"; + return -1; + } + + const char *iss = get_field(tree, "iss"); + if (set->issuers != NULL && *set->issuers != NULL) { + if (iss == NULL) { + *error_r = "Token is missing 'iss' field"; + return -1; + } + if (!str_array_find(set->issuers, iss)) { + *error_r = t_strdup_printf("Issuer '%s' is not allowed", + str_sanitize_utf8(iss, 128)); + return -1; + } + } + + const char *aud = get_field(tree, "aud"); + /* if there is client_id configured, then aud should be present */ + if (set->client_id != NULL && *set->client_id != '\0') { + if (aud == NULL) { + *error_r = "client_id set but aud is missing"; + return -1; + + } + const char *const *auds = t_strsplit_spaces(aud, " "); + if (!str_array_find(auds, set->client_id)) { + *error_r = "client_id not found in aud field"; + return -1; + } + } + + const char *got_scope = get_field(tree, "scope"); + const char *req_scope = set->scope; + + if (req_scope != NULL && *req_scope != '\0') { + if (got_scope == NULL) { + *error_r = "scope set but not found in token"; + return -1; + } + + if (!check_scope(req_scope, got_scope)) { + *error_r = t_strdup_printf("configured scope '%s' missing from token scope '%s'", + req_scope, got_scope); + return -1; + } + } + + /* see if there is azp */ + const char *azp = get_field(tree, "azp"); + if (azp == NULL) + azp = "default"; + else + azp = escape_identifier(azp); + + if (oauth2_validate_signature(set, azp, alg, kid, blobs, error_r) < 0) + return -1; + + oauth2_jwt_copy_fields(fields, tree); + return 0; +} + +int oauth2_try_parse_jwt(const struct oauth2_settings *set, + const char *token, ARRAY_TYPE(oauth2_field) *fields, + bool *is_jwt_r, const char **error_r) +{ + const char *const *blobs = t_strsplit(token, "."); + int ret; + + i_assert(set->key_dict != NULL); + + /* we don't know if it's JWT token yet */ + *is_jwt_r = FALSE; + + if (str_array_length(blobs) != 3) { + *error_r = "Not a JWT token"; + return -1; + } + + /* attempt to decode header */ + buffer_t *header = + t_base64url_decode_str(BASE64_DECODE_FLAG_NO_PADDING, blobs[0]); + + if (header->used == 0) { + *error_r = "Not a JWT token"; + return -1; + } + + struct json_tree *header_tree; + if (oauth2_json_tree_build(header, &header_tree, error_r) < 0) + return -1; + + const char *alg, *kid; + ret = oauth2_jwt_header_process(header_tree, &alg, &kid, error_r); + json_tree_deinit(&header_tree); + if (ret < 0) + return -1; + + /* it is now assumed to be a JWT token */ + *is_jwt_r = TRUE; + + if (kid == NULL) + kid = "default"; + else if (*kid == '\0') { + *error_r = "'kid' field is empty"; + return -1; + } else { + kid = escape_identifier(kid); + } + + /* parse body */ + struct json_tree *body_tree; + buffer_t *body = + t_base64url_decode_str(BASE64_DECODE_FLAG_NO_PADDING, blobs[1]); + if (oauth2_json_tree_build(body, &body_tree, error_r) == -1) + return -1; + ret = oauth2_jwt_body_process(set, alg, kid, fields, body_tree, blobs, + error_r); + json_tree_deinit(&body_tree); + + return ret; +} diff --git a/src/lib-oauth2/oauth2-key-cache.c b/src/lib-oauth2/oauth2-key-cache.c new file mode 100644 index 0000000..e85c210 --- /dev/null +++ b/src/lib-oauth2/oauth2-key-cache.c @@ -0,0 +1,158 @@ +/* Copyright (c) 2020 Dovecot authors, see the included COPYING file */ + +#include "lib.h" +#include "array.h" +#include "llist.h" +#include "buffer.h" +#include "hash.h" +#include "dcrypt.h" +#include "oauth2.h" +#include "oauth2-private.h" + +struct oauth2_key_cache_entry { + const char *key_id; + struct dcrypt_public_key *pubkey; + buffer_t *hmac_key; + struct oauth2_key_cache_entry *prev, *next; +}; + +HASH_TABLE_DEFINE_TYPE(oauth2_key_cache, const char *, + struct oauth2_key_cache_entry *); + +struct oauth2_validation_key_cache { + pool_t pool; + HASH_TABLE_TYPE(oauth2_key_cache) keys; + struct oauth2_key_cache_entry *list_start; +}; + +struct oauth2_validation_key_cache *oauth2_validation_key_cache_init(void) +{ + pool_t pool = pool_alloconly_create( + MEMPOOL_GROWING"oauth2 key cache", 128); + struct oauth2_validation_key_cache *cache = + p_new(pool, struct oauth2_validation_key_cache, 1); + + cache->pool = pool; + hash_table_create(&cache->keys, pool, 8, str_hash, strcmp); + return cache; +} + +void oauth2_validation_key_cache_deinit( + struct oauth2_validation_key_cache **_cache) +{ + struct oauth2_validation_key_cache *cache = *_cache; + *_cache = NULL; + if (cache == NULL) + return; + + /* free resources */ + struct oauth2_key_cache_entry *entry = cache->list_start; + while (entry != NULL) { + if (entry->pubkey != NULL) + dcrypt_key_unref_public(&entry->pubkey); + entry = entry->next; + } + hash_table_destroy(&cache->keys); + pool_unref(&cache->pool); +} + +int oauth2_validation_key_cache_lookup_pubkey( + struct oauth2_validation_key_cache *cache, const char *key_id, + struct dcrypt_public_key **pubkey_r) +{ + if (cache == NULL) + return -1; + + struct oauth2_key_cache_entry *entry = + hash_table_lookup(cache->keys, key_id); + if (entry == NULL || entry->pubkey == NULL) + return -1; + + *pubkey_r = entry->pubkey; + return 0; +} + +int oauth2_validation_key_cache_lookup_hmac_key( + struct oauth2_validation_key_cache *cache, const char *key_id, + const buffer_t **hmac_key_r) +{ + if (cache == NULL) + return -1; + + struct oauth2_key_cache_entry *entry = + hash_table_lookup(cache->keys, key_id); + if (entry == NULL || entry->hmac_key == NULL || + entry->hmac_key->used == 0) + return -1; + + *hmac_key_r = entry->hmac_key; + return 0; +} + +void oauth2_validation_key_cache_insert_pubkey( + struct oauth2_validation_key_cache *cache, const char *key_id, + struct dcrypt_public_key *pubkey) +{ + if (cache == NULL) + return; + + struct oauth2_key_cache_entry *entry = + hash_table_lookup(cache->keys, key_id); + if (entry != NULL) { + dcrypt_key_unref_public(&entry->pubkey); + entry->pubkey = pubkey; + if (entry->hmac_key != NULL) + buffer_set_used_size(entry->hmac_key, 0); + return; + } + entry = p_new(cache->pool, struct oauth2_key_cache_entry, 1); + entry->key_id = p_strdup(cache->pool, key_id); + entry->pubkey = pubkey; + DLLIST_PREPEND(&cache->list_start, entry); + hash_table_insert(cache->keys, entry->key_id, entry); +} + +void oauth2_validation_key_cache_insert_hmac_key( + struct oauth2_validation_key_cache *cache, const char *key_id, + const buffer_t *hmac_key) +{ + if (cache == NULL) + return; + + struct oauth2_key_cache_entry *entry = + hash_table_lookup(cache->keys, key_id); + if (entry != NULL) { + dcrypt_key_unref_public(&entry->pubkey); + if (entry->hmac_key == NULL) { + entry->hmac_key = buffer_create_dynamic( + cache->pool, hmac_key->used); + } else { + buffer_set_used_size(entry->hmac_key, 0); + } + buffer_append(entry->hmac_key, hmac_key->data, hmac_key->used); + return; + } + entry = p_new(cache->pool, struct oauth2_key_cache_entry, 1); + entry->key_id = p_strdup(cache->pool, key_id); + entry->hmac_key = buffer_create_dynamic(cache->pool, hmac_key->used); + buffer_append(entry->hmac_key, hmac_key->data, hmac_key->used); + DLLIST_PREPEND(&cache->list_start, entry); + hash_table_insert(cache->keys, entry->key_id, entry); +} + +int oauth2_validation_key_cache_evict(struct oauth2_validation_key_cache *cache, + const char *key_id) +{ + if (cache == NULL) + return -1; + + struct oauth2_key_cache_entry *entry = + hash_table_lookup(cache->keys, key_id); + if (entry == NULL) + return -1; + if (entry->pubkey != NULL) + dcrypt_key_unref_public(&entry->pubkey); + DLLIST_REMOVE(&cache->list_start, entry); + hash_table_remove(cache->keys, key_id); + return 0; +} diff --git a/src/lib-oauth2/oauth2-private.h b/src/lib-oauth2/oauth2-private.h new file mode 100644 index 0000000..038f9e1 --- /dev/null +++ b/src/lib-oauth2/oauth2-private.h @@ -0,0 +1,50 @@ +#ifndef OAUTH2_PRIVATE_H +#define OAUTH2_PRIVATE_H + +struct json_tree; +struct dcrypt_public_key; + +struct oauth2_request { + pool_t pool; + + const struct oauth2_settings *set; + struct http_client_request *req; + struct json_parser *parser; + struct istream *is; + struct io *io; + + const char *delayed_error; + struct timeout *to_delayed_error; + + const char *username; + const char *key_file_template; + + void (*json_parsed_cb)(struct oauth2_request *, const char *error); + + ARRAY_TYPE(oauth2_field) fields; + char *field_name; + + oauth2_request_callback_t *req_callback; + void *req_context; + /* indicates whether token is valid */ + unsigned int response_status; +}; + +void oauth2_request_parse_json(struct oauth2_request *req); +int oauth2_json_tree_build(const buffer_t *json, struct json_tree **tree_r, + const char **error_r); + +int oauth2_validation_key_cache_lookup_pubkey( + struct oauth2_validation_key_cache *cache, const char *key_id, + struct dcrypt_public_key **pubkey_r); +int oauth2_validation_key_cache_lookup_hmac_key( + struct oauth2_validation_key_cache *cache, const char *key_id, + const buffer_t **hmac_key_r); +void oauth2_validation_key_cache_insert_pubkey( + struct oauth2_validation_key_cache *cache, const char *key_id, + struct dcrypt_public_key *pubkey); +void oauth2_validation_key_cache_insert_hmac_key( + struct oauth2_validation_key_cache *cache, const char *key_id, + const buffer_t *hmac_key); + +#endif diff --git a/src/lib-oauth2/oauth2-request.c b/src/lib-oauth2/oauth2-request.c new file mode 100644 index 0000000..96def56 --- /dev/null +++ b/src/lib-oauth2/oauth2-request.c @@ -0,0 +1,377 @@ +/* Copyright (c) 2019 Dovecot authors, see the included COPYING file */ + +#include "lib.h" +#include "ioloop.h" +#include "istream.h" +#include "str.h" +#include "http-client.h" +#include "http-url.h" +#include "json-parser.h" +#include "oauth2.h" +#include "oauth2-private.h" + +static void oauth2_request_free(struct oauth2_request *req) +{ + timeout_remove(&req->to_delayed_error); + pool_unref(&req->pool); +} + +static void +oauth2_request_callback(struct oauth2_request *req, + struct oauth2_request_result *res) +{ + i_assert(req->req_callback != NULL); + oauth2_request_callback_t *callback = req->req_callback; + req->req_callback = NULL; + callback(res, req->req_context); + oauth2_request_free(req); +} + +static bool +oauth2_request_field_parse(const struct oauth2_field *field, + struct oauth2_request_result *res) +{ + if (strcasecmp(field->name, "expires_in") == 0) { + uint32_t expires_in = 0; + if (str_to_uint32(field->value, &expires_in) < 0) { + res->error = t_strdup_printf( + "Malformed number '%s' in expires_in", + field->value); + return FALSE; + } else { + res->expires_at = ioloop_time + expires_in; + } + } else if (strcasecmp(field->name, "token_type") == 0) { + if (strcasecmp(field->value, "bearer") != 0) { + res->error = t_strdup_printf( + "Expected Bearer token, got '%s'", + field->value); + return FALSE; + } + } + return TRUE; +} + +static void +oauth2_request_continue(struct oauth2_request *req, const char *error) +{ + struct oauth2_request_result res; + i_zero(&res); + + unsigned int status_hi = req->response_status/100; + i_assert(status_hi == 2 || status_hi == 4); + + if (error != NULL) + res.error = error; + else { + const struct oauth2_field *field; + /* see if we can figure out when it expires */ + array_foreach(&req->fields, field) { + if (!oauth2_request_field_parse(field, &res)) + break; + } + res.valid = (status_hi == 2) && res.error == NULL; + } + + res.fields = &req->fields; + + oauth2_request_callback(req, &res); +} + +void oauth2_request_parse_json(struct oauth2_request *req) +{ + enum json_type type; + const char *token, *error; + int ret; + + while((ret = json_parse_next(req->parser, &type, &token)) > 0) { + if (req->field_name == NULL) { + if (type != JSON_TYPE_OBJECT_KEY) break; + /* cannot use t_strdup because we might + have to read more */ + req->field_name = p_strdup(req->pool, token); + } else if (type < JSON_TYPE_STRING) { + /* this should be last allocation */ + p_free(req->pool, req->field_name); + json_parse_skip(req->parser); + } else { + if (!array_is_created(&req->fields)) + p_array_init(&req->fields, req->pool, 4); + struct oauth2_field *field = + array_append_space(&req->fields); + field->name = req->field_name; + req->field_name = NULL; + field->value = p_strdup(req->pool, token); + } + } + + /* read more */ + if (ret == 0) return; + + io_remove(&req->io); + + if (ret > 0) { + (void)json_parser_deinit(&req->parser, &error); + error = "Invalid response data"; + } else if (i_stream_read_eof(req->is) && + req->is->v_offset == 0 && req->is->stream_errno == 0) { + /* discard error, empty response is OK. */ + (void)json_parser_deinit(&req->parser, &error); + error = NULL; + } else if (json_parser_deinit(&req->parser, &error) == 0) { + error = NULL; + } else { + i_assert(error != NULL); + } + + i_stream_unref(&req->is); + + req->json_parsed_cb(req, error); +} + +static void +oauth2_request_response(const struct http_response *response, + struct oauth2_request *req) +{ + req->response_status = response->status; + unsigned int status_hi = req->response_status/100; + + if (status_hi != 2 && status_hi != 4) { + /* Unexpected internal error */ + struct oauth2_request_result res = { + .error = http_response_get_message(response), + }; + oauth2_request_callback(req, &res); + return; + } + + if (response->payload != NULL) { + req->is = response->payload; + i_stream_ref(req->is); + } else { + req->is = i_stream_create_from_data("", 0); + } + + p_array_init(&req->fields, req->pool, 1); + req->parser = json_parser_init(req->is); + req->json_parsed_cb = oauth2_request_continue; + req->io = io_add_istream(req->is, oauth2_request_parse_json, req); + oauth2_request_parse_json(req); +} + +static void +oauth2_request_fail(struct oauth2_request *req) +{ + struct oauth2_request_result res = { + .error = "No token provided", + .valid = FALSE, + }; + oauth2_request_callback(req, &res); +} + +static void +oauth2_request_set_headers(struct oauth2_request *req, + const struct oauth2_request_input *input) +{ + if (!req->set->send_auth_headers) + return; + if (input->service != NULL) { + http_client_request_add_header( + req->req, "X-Dovecot-Auth-Service", input->service); + } + if (input->local_ip.family != 0) { + const char *addr; + if (net_ipport2str(&input->local_ip, input->local_port, + &addr) == 0) { + http_client_request_add_header( + req->req, "X-Dovecot-Auth-Local", addr); + } + } + if (input->remote_ip.family != 0) { + const char *addr; + if (net_ipport2str(&input->remote_ip, input->remote_port, + &addr) == 0) { + http_client_request_add_header( + req->req, "X-Dovecot-Auth-Remote", addr); + } + } +} + +static struct oauth2_request * +oauth2_request_start(const struct oauth2_settings *set, + const struct oauth2_request_input *input, + oauth2_request_callback_t *callback, + void *context, + pool_t p, + const char *method, + const char *url, + const string_t *payload, + bool add_auth_bearer) +{ + pool_t pool = (p == NULL) ? + pool_alloconly_create_clean("oauth2 request", 1024) : p; + struct oauth2_request *req = + p_new(pool, struct oauth2_request, 1); + + req->pool = pool; + req->set = set; + req->req_callback = callback; + req->req_context = context; + + if (!oauth2_valid_token(input->token)) { + req->to_delayed_error = + timeout_add_short(0, oauth2_request_fail, req); + return req; + } + + req->req = http_client_request_url_str(req->set->client, method, url, + oauth2_request_response, req); + + oauth2_request_set_headers(req, input); + + if (payload != NULL && strcmp(method, "POST") == 0) { + struct istream *is = i_stream_create_from_string(payload); + + http_client_request_add_header( + req->req, "Content-Type", + "application/x-www-form-urlencoded"); + + http_client_request_set_payload(req->req, is, FALSE); + i_stream_unref(&is); + } + if (add_auth_bearer && + http_client_request_get_origin_url(req->req)->user == NULL && + set->introspection_mode == INTROSPECTION_MODE_GET_AUTH) { + http_client_request_add_header(req->req, + "Authorization", + t_strdup_printf("Bearer %s", + input->token)); + } + http_client_request_set_timeout_msecs(req->req, + req->set->timeout_msecs); + http_client_request_submit(req->req); + + return req; +} + +#undef oauth2_refresh_start +struct oauth2_request * +oauth2_refresh_start(const struct oauth2_settings *set, + const struct oauth2_request_input *input, + oauth2_request_callback_t *callback, void *context) +{ + string_t *payload = t_str_new(128); + + str_append(payload, "grant_type=refresh_token&refresh_token="); + http_url_escape_param(payload, input->token); + + return oauth2_request_start(set, input, callback, context, NULL, + "POST", set->refresh_url, NULL, FALSE); +} + +#undef oauth2_introspection_start +struct oauth2_request * +oauth2_introspection_start(const struct oauth2_settings *set, + const struct oauth2_request_input *input, + oauth2_request_callback_t *callback, void *context) +{ + string_t *enc; + const char *url; + const char *method; + string_t *payload = NULL; + pool_t p = NULL; + + switch (set->introspection_mode) { + case INTROSPECTION_MODE_GET: + enc = t_str_new(64); + str_append(enc, set->introspection_url); + http_url_escape_param(enc, input->token); + if (*set->client_id != '\0') { + str_append(enc, "&client_id="); + http_url_escape_param(enc, set->client_id); + } + if (*set->client_secret != '\0') { + str_append(enc, "&client_secret="); + http_url_escape_param(enc, set->client_secret); + } + url = str_c(enc); + method = "GET"; + break; + case INTROSPECTION_MODE_GET_AUTH: + url = set->introspection_url; + method = "GET"; + break; + case INTROSPECTION_MODE_POST: + p = pool_alloconly_create_clean("oauth2 request", 1024); + payload = str_new(p, strlen(input->token)+6); + str_append(payload, "token="); + http_url_escape_param(payload, input->token); + url = set->introspection_url; + method = "POST"; + break; + default: + i_unreached(); + break; + } + + return oauth2_request_start(set, input, callback, context, p, + method, url, payload, TRUE); +} + +#undef oauth2_token_validation_start +struct oauth2_request * +oauth2_token_validation_start(const struct oauth2_settings *set, + const struct oauth2_request_input *input, + oauth2_request_callback_t *callback, + void *context) +{ + string_t *enc = t_str_new(64); + + str_append(enc, set->tokeninfo_url); + http_url_escape_param(enc, input->token); + + return oauth2_request_start(set, input, callback, context, + NULL, "GET", str_c(enc), NULL, TRUE); +} + +#undef oauth2_passwd_grant_start +struct oauth2_request * +oauth2_passwd_grant_start(const struct oauth2_settings *set, + const struct oauth2_request_input *input, + const char *username, const char *password, + oauth2_request_callback_t *callback, void *context) +{ + pool_t pool = pool_alloconly_create_clean("oauth2 request", 1024); + string_t *payload = str_new(pool, 128); + + /* add token */ + str_append(payload, "grant_type=password&username="); + http_url_escape_param(payload, username); + str_append(payload, "&password="); + http_url_escape_param(payload, password); + if (*set->client_id != '\0') { + str_append(payload, "&client_id="); + http_url_escape_param(payload, set->client_id); + } + if (*set->client_secret != '\0') { + str_append(payload, "&client_secret="); + http_url_escape_param(payload, set->client_secret); + } + if (set->scope[0] != '\0') { + str_append(payload, "&scope="); + http_url_escape_param(payload, set->scope); + } + + return oauth2_request_start(set, input, callback, context, + pool, "POST", set->grant_url, + payload, FALSE); +} + +void oauth2_request_abort(struct oauth2_request **_req) +{ + struct oauth2_request *req = *_req; + *_req = NULL; + + http_client_request_abort(&req->req); + oauth2_request_free(req); +} diff --git a/src/lib-oauth2/oauth2.c b/src/lib-oauth2/oauth2.c new file mode 100644 index 0000000..b96995e --- /dev/null +++ b/src/lib-oauth2/oauth2.c @@ -0,0 +1,41 @@ +/* Copyright (c) 2017-2018 Dovecot authors, see the included COPYING file */ + +#include "lib.h" +#include "buffer.h" +#include "istream.h" +#include "json-tree.h" +#include "oauth2.h" +#include "oauth2-private.h" + +int oauth2_json_tree_build(const buffer_t *json, struct json_tree **tree_r, + const char **error_r) +{ + struct istream *is = i_stream_create_from_buffer(json); + struct json_parser *parser = json_parser_init(is); + struct json_tree *tree = json_tree_init(); + enum json_type type; + const char *value; + int ret; + + while ((ret = json_parse_next(parser, &type, &value)) > 0) { + /* this is safe to reuse here because it gets rewritten in while + loop */ + ret = json_tree_append(tree, type, value); + i_assert(ret == 0); + } + i_assert(ret != 0); + ret = json_parser_deinit(&parser, error_r); + i_stream_unref(&is); + if (ret != 0) + json_tree_deinit(&tree); + else + *tree_r = tree; + return ret; +} + +bool oauth2_valid_token(const char *token) +{ + if (token == NULL || *token == '\0' || strpbrk(token, "\r\n") != NULL) + return FALSE; + return TRUE; +} diff --git a/src/lib-oauth2/oauth2.h b/src/lib-oauth2/oauth2.h new file mode 100644 index 0000000..3d1d3ea --- /dev/null +++ b/src/lib-oauth2/oauth2.h @@ -0,0 +1,149 @@ +#ifndef OAUTH2_H +#define OAUTH2_H + +#include "net.h" + +struct dict; +struct oauth2_request; +struct oauth2_validation_key_cache; + +struct oauth2_field { + const char *name; + const char *value; +}; + +ARRAY_DEFINE_TYPE(oauth2_field, struct oauth2_field); + +struct oauth2_settings { + struct http_client *client; + /* GET tokeninfo from this URL, token is appended to URL + http://some.host/path?access_token= */ + const char *tokeninfo_url; + /* POST grant password here, needs user credentials and client_* + settings */ + const char *grant_url; + /* GET more information from this URL, uses Bearer authentication */ + const char *introspection_url; + /* POST refresh here, needs refresh token and client_* settings */ + const char *refresh_url; + /* client identificator for oauth2 server */ + const char *client_id; + /* client secret for oauth2 server */ + const char *client_secret; + /* access request scope for oauth2 server (optional) */ + const char *scope; + /* key dict for looking up validation keys */ + struct dict *key_dict; + /* cache for validation keys */ + struct oauth2_validation_key_cache *key_cache; + /* valid issuer names */ + const char *const *issuers; + + enum { + INTROSPECTION_MODE_GET_AUTH, + INTROSPECTION_MODE_GET, + INTROSPECTION_MODE_POST, + INTROSPECTION_MODE_LOCAL, + } introspection_mode; + unsigned int timeout_msecs; + /* Should X-Dovecot-Auth-* headers be sent */ + bool send_auth_headers; + /* Should use grant password mechanism for authentication */ + bool use_grant_password; +}; + + +struct oauth2_request_result { + /* Oauth2 server response fields */ + ARRAY_TYPE(oauth2_field) *fields; + /* Non-NULL if there was an unexpected internal error. */ + const char *error; + /* timestamp token expires at */ + time_t expires_at; + /* User authenticated successfully. Implies that error==NULL. */ + bool valid:1; +}; + +struct oauth2_request_input { + const char *token; + const char *service; + struct ip_addr local_ip, real_local_ip, remote_ip, real_remote_ip; + in_port_t local_port, real_local_port, remote_port, real_remote_port; +}; + +typedef void +oauth2_request_callback_t(struct oauth2_request_result*, void*); + +bool oauth2_valid_token(const char *token); + +struct oauth2_request* +oauth2_passwd_grant_start(const struct oauth2_settings *set, + const struct oauth2_request_input *input, + const char *username, + const char *password, + oauth2_request_callback_t *callback, + void *context); +#define oauth2_passwd_grant_start(set, input, username, password, callback, \ + context) \ + oauth2_passwd_grant_start( \ + set, input - CALLBACK_TYPECHECK( \ + callback, void(*)(struct oauth2_request_result*, \ + typeof(context))), \ + username, password, \ + (oauth2_request_callback_t*)callback, (void*)context); + +struct oauth2_request* +oauth2_token_validation_start(const struct oauth2_settings *set, + const struct oauth2_request_input *input, + oauth2_request_callback_t *callback, + void *context); +#define oauth2_token_validation_start(set, input, callback, context) \ + oauth2_token_validation_start( \ + set, input - CALLBACK_TYPECHECK( \ + callback, void(*)(struct oauth2_request_result*, \ + typeof(context))), \ + (oauth2_request_callback_t*)callback, (void*)context); + +struct oauth2_request* +oauth2_introspection_start(const struct oauth2_settings *set, + const struct oauth2_request_input *input, + oauth2_request_callback_t *callback, + void *context); +#define oauth2_introspection_start(set, input, callback, context) \ + oauth2_introspection_start( \ + set, input - CALLBACK_TYPECHECK( \ + callback, void(*)(struct oauth2_request_result*, \ + typeof(context))), \ + (oauth2_request_callback_t*)callback, (void*)context); + +struct oauth2_request * +oauth2_refresh_start(const struct oauth2_settings *set, + const struct oauth2_request_input *input, + oauth2_request_callback_t *callback, + void *context); +#define oauth2_refresh_start(set, input, callback, context) \ + oauth2_refresh_start( \ + set, input - CALLBACK_TYPECHECK( \ + callback, void(*)(struct oauth2_request_result*, \ + typeof(context))), \ + (oauth2_request_callback_t*)callback, (void*)context); + +/* Abort without calling callback, use this to cancel the request */ +void oauth2_request_abort(struct oauth2_request **); + +int oauth2_try_parse_jwt(const struct oauth2_settings *set, + const char *token, ARRAY_TYPE(oauth2_field) *fields, + bool *is_jwt_r, const char **error_r); + +/* Initialize validation key cache */ +struct oauth2_validation_key_cache *oauth2_validation_key_cache_init(void); + +/* Evict given key ID from cache, returns 0 on successful eviction */ +int oauth2_validation_key_cache_evict(struct oauth2_validation_key_cache *cache, + const char *key_id); + +/* Deinitialize validation key cache */ +void oauth2_validation_key_cache_deinit( + struct oauth2_validation_key_cache **_cache); + +#endif diff --git a/src/lib-oauth2/test-oauth2-json.c b/src/lib-oauth2/test-oauth2-json.c new file mode 100644 index 0000000..87caedc --- /dev/null +++ b/src/lib-oauth2/test-oauth2-json.c @@ -0,0 +1,104 @@ +/* Copyright (c) 2015-2018 Dovecot authors, see the included COPYING file */ + +#include "lib.h" +#include "array.h" +#include "json-parser.h" +#include "oauth2.h" +#include "oauth2-private.h" +#include "test-common.h" + +static void +test_oauth_json_valid_parsed(struct oauth2_request *req ATTR_UNUSED, + const char *error) +{ + test_assert(error == NULL); +} + +static void test_oauth2_json_valid(void) +{ + static const char *test_input = + "{\"access_token\":\"9a2dea3c-f8be-4271-b9c8-5b37da4f2f7e\"," + "\"grant_type\":\"authorization_code\"," + "\"openid\":\"\"," + "\"scope\":[\"openid\",\"profile\",\"email\"]," + "\"profile\":\"\"," + "\"realm\":\"/employees\"," + "\"token_type\":\"Bearer\"," + "\"expires_in\":2377," + "\"client_id\":\"mosaic\"," + "\"email\":\"\"," + "\"extensions\":" + "{\"algorithm\":\"cuttlefish\"," + "\"tentacles\":8" + "}" + "}"; + static const struct oauth2_field fields[] = { + { .name = "access_token", + .value = "9a2dea3c-f8be-4271-b9c8-5b37da4f2f7e" }, + { .name = "grant_type", + .value = "authorization_code" }, + { .name = "openid", + .value = "" }, + { .name = "profile", + .value = "" }, + { .name = "realm", + .value = "/employees" }, + { .name = "token_type", + .value = "Bearer" }, + { .name = "expires_in", + .value = "2377" }, + { .name = "client_id", + .value = "mosaic" }, + { .name = "email", + .value = "" }, + }; + static const unsigned int fields_count = N_ELEMENTS(fields); + struct oauth2_request *req; + const struct oauth2_field *pfields; + unsigned int count, i; + pool_t pool; + size_t pos; + + test_begin("oauth json skip"); + + /* Create mock request */ + pool = pool_alloconly_create_clean("oauth2 json test", 1024); + req = p_new(pool, struct oauth2_request, 1); + req->pool = pool; + p_array_init(&req->fields, req->pool, 1); + req->is = test_istream_create_data(test_input, strlen(test_input)); + req->parser = json_parser_init(req->is); + req->json_parsed_cb = test_oauth_json_valid_parsed; + + /* Parse the JSON response */ + for (pos = 0; pos <= strlen(test_input); pos +=2) { + test_istream_set_size(req->is, pos); + oauth2_request_parse_json(req); + if (req->is == NULL) + break; + } + + /* Verify the parsed fields */ + pfields = array_get(&req->fields, &count); + test_assert(count == fields_count); + if (count > fields_count) + count = fields_count; + for (i = 0; i < count; i++) { + test_assert(strcmp(pfields[i].name, fields[i].name) == 0); + test_assert(strcmp(pfields[i].value, fields[i].value) == 0); + } + + /* Clean up */ + pool_unref(&req->pool); + + test_end(); +} + +int main(void) +{ + static void (*const test_functions[])(void) = { + test_oauth2_json_valid, + NULL + }; + return test_run(test_functions); +} diff --git a/src/lib-oauth2/test-oauth2-jwt.c b/src/lib-oauth2/test-oauth2-jwt.c new file mode 100644 index 0000000..021c91f --- /dev/null +++ b/src/lib-oauth2/test-oauth2-jwt.c @@ -0,0 +1,919 @@ +/* Copyright (c) 2020 Dovecot authors, see the included COPYING file */ + +#include "lib.h" +#include "buffer.h" +#include "str.h" +#include "ostream.h" +#include "hmac.h" +#include "sha2.h" +#include "base64.h" +#include "randgen.h" +#include "array.h" +#include "json-parser.h" +#include "iso8601-date.h" +#include "oauth2.h" +#include "oauth2-private.h" +#include "dcrypt.h" +#include "dict.h" +#include "dict-private.h" +#include "test-common.h" +#include "unlink-directory.h" + +#include <sys/stat.h> +#include <sys/types.h> + +#define base64url_encode_str(str, dest) \ + base64url_encode(BASE64_ENCODE_FLAG_NO_PADDING, SIZE_MAX, (str), \ + strlen((str)), (dest)) + +/** + * Test keypair used only for this test. + */ +static const char *rsa_public_key = +"-----BEGIN PUBLIC KEY-----\n" +"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnzyis1ZjfNB0bBgKFMSv\n" +"vkTtwlvBsaJq7S5wA+kzeVOVpVWwkWdVha4s38XM/pa/yr47av7+z3VTmvDRyAHc\n" +"aT92whREFpLv9cj5lTeJSibyr/Mrm/YtjCZVWgaOYIhwrXwKLqPr/11inWsAkfIy\n" +"tvHWTxZYEcXLgAXFuUuaS3uF9gEiNQwzGTU1v0FqkqTBr4B8nW3HCN47XUu0t8Y0\n" +"e+lf4s4OxQawWD79J9/5d3Ry0vbV3Am1FtGJiJvOwRsIfVChDpYStTcHTCMqtvWb\n" +"V6L11BWkpzGXSW4Hv43qa+GSYOD2QU68Mb59oSk2OB+BtOLpJofmbGEGgvmwyCI9\n" +"MwIDAQAB\n" +"-----END PUBLIC KEY-----"; +static const char *rsa_private_key = +"-----BEGIN PRIVATE KEY-----\n" +"MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCfPKKzVmN80HRs\n" +"GAoUxK++RO3CW8GxomrtLnAD6TN5U5WlVbCRZ1WFrizfxcz+lr/Kvjtq/v7PdVOa\n" +"8NHIAdxpP3bCFEQWku/1yPmVN4lKJvKv8yub9i2MJlVaBo5giHCtfAouo+v/XWKd\n" +"awCR8jK28dZPFlgRxcuABcW5S5pLe4X2ASI1DDMZNTW/QWqSpMGvgHydbccI3jtd\n" +"S7S3xjR76V/izg7FBrBYPv0n3/l3dHLS9tXcCbUW0YmIm87BGwh9UKEOlhK1NwdM\n" +"Iyq29ZtXovXUFaSnMZdJbge/jepr4ZJg4PZBTrwxvn2hKTY4H4G04ukmh+ZsYQaC\n" +"+bDIIj0zAgMBAAECggEAKIBGrbCSW2O1yOyQW9nvDUkA5EdsS58Q7US7bvM4iWpu\n" +"DIBwCXur7/VuKnhn/HUhURLzj/JNozynSChqYyG+CvL+ZLy82LUE3ZIBkSdv/vFL\n" +"Ft+VvvRtf1EcsmoqenkZl7aN7HD7DJeXBoz5tyVQKuH17WW0fsi9StGtCcUl+H6K\n" +"zV9Gif0Kj0uLQbCg3THRvKuueBTwCTdjoP0PwaNADgSWb3hJPeLMm/yII4tIMGbO\n" +"w+xd9wJRl+ZN9nkNtQMxszFGdKjedB6goYLQuP0WRZx+YtykaVJdM75bDUvsQar4\n" +"9Pc21Fp7UVk/CN11DX/hX3TmTJAUtqYADliVKkTbCQKBgQDLU48tBxm3g1CdDM/P\n" +"ZIEmpA3Y/m7e9eX7M1Uo/zDh4G/S9a4kkX6GQY2dLFdCtOS8M4hR11Io7MceBKDi\n" +"djorTZ5zJPQ8+b9Rm+1GlaucGNwRW0cQk2ltT2ksPmJnQn2xvM9T8vE+a4A/YGzw\n" +"mZOfpoVGykWs/tbSzU2aTaOybQKBgQDIfRf6OmirGPh59l+RSuDkZtISF/51mCV/\n" +"S1M4DltWDwhjC2Y2T+meIsb/Mjtz4aVNz0EHB8yvn0TMGr94Uwjv4uBdpVSwz+xL\n" +"hHL7J4rpInH+i0gxa0N+rGwsPwI8wJG95wLY+Kni5KCuXQw55uX1cqnnsahpRZFZ\n" +"EerBXhjqHwKBgBmEjiaHipm2eEqNjhMoOPFBi59dJ0sCL2/cXGa9yEPA6Cfgv49F\n" +"V0zAM2azZuwvSbm4+fXTgTMzrDW/PPXPArPmlOk8jQ6OBY3XdOrz48q+b/gZrYyO\n" +"A6A9ZCSyW6U7+gxxds/BYLeFxF2v21xC2f0iZ/2faykv/oQMUh34en/tAoGACqVZ\n" +"2JexZyR0TUWf3X80YexzyzIq+OOTWicNzDQ29WLm9xtr2gZ0SUlfd72bGpQoyvDu\n" +"awkm/UxfwtbIxALkvpg1gcN9s8XWrkviLyPyZF7H3tRWiQlBFEDjnZXa8I7pLkRO\n" +"Cmdp3fp17cxTEeAI5feovfzZDH39MdWZuZrdh9ECgYBTEv8S7nK8wrxIC390kroV\n" +"52eBwzckQU2mWa0thUtaGQiU1EYPCSDcjkrLXwB72ft0dW57KyWtvrB6rt1ORgOL\n" +"eI5hFbwdGQhCHTrAR1vG3SyFPMAm+8JB+sGOD/fvjtZKx//MFNweKFNEF0C/o6Z2\n" +"FXj90PlgF8sCQut36ZfuIQ==\n" +"-----END PRIVATE KEY-----"; + +static buffer_t *hs_sign_key = NULL; + +static struct dict *keys_dict = NULL; + +static bool skip_dcrypt = FALSE; + +static struct oauth2_validation_key_cache *key_cache = NULL; + +static int parse_jwt_token(struct oauth2_request *req, const char *token, + bool *is_jwt_r, const char **error_r) +{ + struct oauth2_settings set; + + i_zero(&set); + set.key_dict = keys_dict; + set.key_cache = key_cache; + i_zero(req); + req->pool = pool_datastack_create(); + req->set = &set; + t_array_init(&req->fields, 8); + return oauth2_try_parse_jwt(&set, token, &req->fields, is_jwt_r, + error_r); +} + +static void test_jwt_token(const char *token) +{ + /* then see what the parser likes it */ + struct oauth2_request req; + const char *error = NULL; + + bool is_jwt; + test_assert(parse_jwt_token(&req, token, &is_jwt, &error) == 0); + test_assert(is_jwt == TRUE); + test_assert(error == NULL); + + /* check fields */ + test_assert(array_is_created(&req.fields)); + if (array_is_created(&req.fields)) { + const struct oauth2_field *field; + bool got_sub = FALSE; + array_foreach(&req.fields, field) { + if (strcmp(field->name, "sub") == 0) { + test_assert_strcmp(field->value, "testuser"); + got_sub = TRUE; + } + } + test_assert(got_sub == TRUE); + } + + if (error != NULL) + i_error("%s", error); +} + +static buffer_t *create_jwt_token_kid(const char *algo, const char *kid) +{ + /* make a token */ + buffer_t *tokenbuf = t_buffer_create(64); + + /* header */ + base64url_encode_str( + t_strdup_printf( + "{\"alg\":\"%s\",\"typ\":\"JWT\",\"kid\":\"%s\"}", + algo, kid), + tokenbuf); + buffer_append(tokenbuf, ".", 1); + + /* body */ + base64url_encode_str( + t_strdup_printf("{\"sub\":\"testuser\","\ + "\"iat\":%"PRIdTIME_T"," + "\"exp\":%"PRIdTIME_T"}", + time(NULL), time(NULL)+600), + tokenbuf); + return tokenbuf; +} + +static buffer_t *create_jwt_token(const char *algo) +{ + /* make a token */ + buffer_t *tokenbuf = t_buffer_create(64); + + /* header */ + base64url_encode_str( + t_strdup_printf("{\"alg\":\"%s\",\"typ\":\"JWT\"}", algo), + tokenbuf); + buffer_append(tokenbuf, ".", 1); + + /* body */ + base64url_encode_str( + t_strdup_printf("{\"sub\":\"testuser\","\ + "\"iat\":%"PRIdTIME_T"," + "\"exp\":%"PRIdTIME_T"}", + time(NULL), time(NULL)+600), + tokenbuf); + return tokenbuf; +} + +static void +append_key_value(string_t *dest, const char *key, const char *value, bool str) +{ + str_append_c(dest, '"'); + json_append_escaped(dest, key); + str_append(dest, "\":"); + if (str) + str_append_c(dest, '"'); + json_append_escaped(dest, value); + if (str) + str_append_c(dest, '"'); + +} + +#define create_jwt_token_fields(algo, exp, iat, nbf, fields) \ + create_jwt_token_fields_kid(algo, "default", exp, iat, nbf, fields) +static buffer_t * +create_jwt_token_fields_kid(const char *algo, const char *kid, time_t exp, time_t iat, + time_t nbf, ARRAY_TYPE(oauth2_field) *fields) +{ + const struct oauth2_field *field; + buffer_t *tokenbuf = t_buffer_create(64); + string_t *hdr = t_str_new(32); + str_printfa(hdr, "{\"alg\":\"%s\",\"typ\":\"JWT\"", algo); + if (kid != NULL && *kid != '\0') { + str_append(hdr, ",\"kid\":\""); + json_append_escaped(hdr, kid); + str_append_c(hdr, '"'); + } + str_append(hdr, "}"); + base64url_encode_str(str_c(hdr), tokenbuf); + buffer_append(tokenbuf, ".", 1); + + string_t *bodybuf = t_str_new(64); + str_append_c(bodybuf, '{'); + if (exp > 0) { + append_key_value(bodybuf, "exp", dec2str(exp), FALSE); + } + if (iat > 0) { + if (exp > 0) + str_append_c(bodybuf, ','); + append_key_value(bodybuf, "iat", dec2str(iat), FALSE); + } + if (nbf > 0) { + if (exp > 0 || iat > 0) + str_append_c(bodybuf, ','); + append_key_value(bodybuf, "nbf", dec2str(nbf), FALSE); + } + array_foreach(fields, field) { + if (str_data(bodybuf)[bodybuf->used-1] != '{') + str_append_c(bodybuf, ','); + append_key_value(bodybuf, field->name, field->value, TRUE); + } + str_append_c(bodybuf, '}'); + base64url_encode_str(str_c(bodybuf), tokenbuf); + + return tokenbuf; +} + +#define save_key(algo, key) save_key_to(algo, "default", (key)) +#define save_key_to(algo, name, key) save_key_azp_to(algo, "default", name, (key)) +static void save_key_azp_to(const char *algo, const char *azp, + const char *name, const char *keydata) +{ + const char *error; + struct dict_op_settings set = { + .username = "testuser", + }; + struct dict_transaction_context *ctx = + dict_transaction_begin(keys_dict, &set); + algo = t_str_ucase(algo); + dict_set(ctx, t_strconcat(DICT_PATH_SHARED, azp, "/", algo, "/", + name, NULL), + keydata); + if (dict_transaction_commit(&ctx, &error) < 0) + i_error("dict_set(%s) failed: %s", name, error); +} + +static void sign_jwt_token_hs256(buffer_t *tokenbuf, buffer_t *key) +{ + i_assert(key != NULL); + buffer_t *sig = t_hmac_buffer(&hash_method_sha256, key->data, key->used, + tokenbuf); + buffer_append(tokenbuf, ".", 1); + base64url_encode(BASE64_ENCODE_FLAG_NO_PADDING, SIZE_MAX, + sig->data, sig->used, tokenbuf); +} + +static void sign_jwt_token_hs384(buffer_t *tokenbuf, buffer_t *key) +{ + i_assert(key != NULL); + buffer_t *sig = t_hmac_buffer(&hash_method_sha384, key->data, key->used, + tokenbuf); + buffer_append(tokenbuf, ".", 1); + base64url_encode(BASE64_ENCODE_FLAG_NO_PADDING, SIZE_MAX, + sig->data, sig->used, tokenbuf); +} + +static void sign_jwt_token_hs512(buffer_t *tokenbuf, buffer_t *key) +{ + i_assert(key != NULL); + buffer_t *sig = t_hmac_buffer(&hash_method_sha512, key->data, key->used, + tokenbuf); + buffer_append(tokenbuf, ".", 1); + base64url_encode(BASE64_ENCODE_FLAG_NO_PADDING, SIZE_MAX, + sig->data, sig->used, tokenbuf); +} + +static void test_jwt_hs_token(void) +{ + test_begin("JWT HMAC token"); + + buffer_t *sign_key_384 = t_buffer_create(384/8); + void *ptr = buffer_append_space_unsafe(sign_key_384, 384/8); + random_fill(ptr, 384/8); + buffer_t *b64_key = t_base64_encode(0, SIZE_MAX, + sign_key_384->data, + sign_key_384->used); + save_key_to("HS384", "default", str_c(b64_key)); + buffer_t *sign_key_512 = t_buffer_create(512/8); + ptr = buffer_append_space_unsafe(sign_key_512, 512/8); + random_fill(ptr, 512/8); + b64_key = t_base64_encode(0, SIZE_MAX, + sign_key_512->data, + sign_key_512->used); + save_key_to("HS512", "default", str_c(b64_key)); + /* make a token */ + buffer_t *tokenbuf = create_jwt_token("HS256"); + /* sign it */ + sign_jwt_token_hs256(tokenbuf, hs_sign_key); + test_jwt_token(str_c(tokenbuf)); + + tokenbuf = create_jwt_token("HS384"); + sign_jwt_token_hs384(tokenbuf, sign_key_384); + test_jwt_token(str_c(tokenbuf)); + + tokenbuf = create_jwt_token("HS512"); + sign_jwt_token_hs512(tokenbuf, sign_key_512); + test_jwt_token(str_c(tokenbuf)); + + test_end(); +} + +static void test_jwt_token_escape(void) +{ + struct test_case { + const char *azp; + const char *alg; + const char *kid; + const char *esc_azp; + const char *esc_kid; + } test_cases[] = { + { "", "hs256", "", "default", "default" }, + { "", "hs256", "test", "default", "test" }, + { "test", "hs256", "test", "test", "test" }, + { + "http://test.unit/local%key", + "hs256", + "http://test.unit/local%key", + "http:%2f%2ftest.unit%2flocal%25key", + "http:%2f%2ftest.unit%2flocal%25key" + }, + { "../", "hs256", "../", "..%2f", "..%2f" }, + }; + + test_begin("JWT token escaping"); + + buffer_t *b64_key = + t_base64_encode(0, SIZE_MAX, hs_sign_key->data, hs_sign_key->used); + ARRAY_TYPE(oauth2_field) fields; + t_array_init(&fields, 8); + + for (size_t i = 0; i < N_ELEMENTS(test_cases); i++) { + const struct test_case *test_case = &test_cases[i]; + array_clear(&fields); + struct oauth2_field *field = array_append_space(&fields); + field->name = "sub"; + field->value = "testuser"; + if (*test_case->azp != '\0') { + field = array_append_space(&fields); + field->name = "azp"; + field->value = test_case->azp; + } + if (*test_case->kid != '\0') { + field = array_append_space(&fields); + field->name = "kid"; + field->value = test_case->kid; + } + save_key_azp_to(test_case->alg, test_case->esc_azp, test_case->esc_kid, + str_c(b64_key)); + buffer_t *token = create_jwt_token_fields_kid(test_case->alg, + test_case->kid, + time(NULL)+500, + time(NULL)-500, + 0, &fields); + sign_jwt_token_hs256(token, hs_sign_key); + test_jwt_token(str_c(token)); + } + + test_end(); +} + +static void test_jwt_broken_token(void) +{ + struct test_cases { + const char *token; + bool is_jwt; + } test_cases[] = { + { /* empty token */ + .token = "", + .is_jwt = FALSE + }, + { /* not base64 */ + .token = "{\"alg\":\"HS256\":\"typ\":\"JWT\"}", + .is_jwt = FALSE + }, + { /* not jwt */ + .token = "aGVsbG8sIHdvcmxkCg", + .is_jwt = FALSE + }, + { /* no alg field */ + .token = "eyJ0eXAiOiAiSldUIn0.e30.e30", + .is_jwt = FALSE + }, + { /* typ field is wrong */ + .token = "e3R5cDogamtzLCBhbGc6IEhTMjU2fQ." + "eyJhbGdvIjogIldURiIsICJ0eXAiOiAiSldUIn0." + "q2wwwWWJVJxqw-J3uQ0DdlIyWfoZ7Z0QrdzvMW_B-jo", + .is_jwt = FALSE + }, + { /* unknown algorithm */ + .token = "eyJ0eXAiOiAiSldUIiwgImFsZyI6ICJXVEYifQ." + "eyJhbGdvIjogIldURiIsICJ0eXAiOiAiSldUIn0." + "q2wwwWWJVJxqw-J3uQ0DdlIyWfoZ7Z0QrdzvMW_B-jo", + .is_jwt = TRUE + }, + { /* truncated base64 */ + .token = "yJhbGciOiJIUzI1NiIsInR5", + .is_jwt = FALSE + }, + { /* missing body and signature */ + .token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9", + .is_jwt = FALSE + }, + { /* empty body and signature */ + .token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..", + .is_jwt = TRUE + }, + { /* empty signature */ + .token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." + "eyJleHAiOjE1ODEzMzA3OTN9.", + .is_jwt = TRUE + }, + { /* bad signature */ + .token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." + "eyJleHAiOjE1ODEzMzA3OTN9." + "q2wwwWWJVJxqw-J3uQ0DdlIyWfoZ7Z0QrdzvMW_B-jo", + .is_jwt = TRUE + }, + { /* algorithm is 'none' */ + .token = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0." + "eyJleHAiOjE1ODEzMzA3OTN9.", + .is_jwt = TRUE + } + }; + + test_begin("JWT broken tokens"); + + for (size_t i = 0; i < N_ELEMENTS(test_cases); i++) T_BEGIN { + struct test_cases *test_case = &test_cases[i]; + struct oauth2_request req; + const char *error = NULL; + bool is_jwt; + test_assert_idx(parse_jwt_token(&req, test_case->token, + &is_jwt, &error) != 0, i); + test_assert_idx(test_case->is_jwt == is_jwt, i); + test_assert_idx(error != NULL, i); + } T_END; + + test_end(); +} + +static void test_jwt_bad_valid_token(void) +{ + test_begin("JWT bad token tests"); + time_t now = time(NULL); + + struct test_cases { + time_t exp; + time_t iat; + time_t nbf; + const char *key_values[20]; + const char *error; + } test_cases[] = + { + { /* "empty" token */ + .exp = 0, + .iat = 0, + .nbf = 0, + .key_values = { NULL }, + .error = "Missing 'sub' field", + }, + { /* missing sub field */ + .exp = now+500, + .iat = 0, + .nbf = 0, + .key_values = { NULL }, + .error = "Missing 'sub' field", + }, + { /* no expiration */ + .key_values = { + "sub", "testuser", + NULL + }, + .error = "Missing 'exp' field", + }, + { /* non-ISO date as iat */ + .exp = now+500, + .iat = 0, + .nbf = 0, + .key_values = { "sub", "testuser", "iat", + "1.1.2019 16:00", NULL }, + .error = "Malformed 'iat' field" + }, + { /* expired token */ + .exp = now-500, + .iat = 0, + .nbf = 0, + .key_values = { "sub", "testuser", NULL }, + .error = "Token has expired", + }, + { /* future token */ + .exp = now+1000, + .iat = now+500, + .nbf = 0, + .key_values = { "sub", "testuser", NULL }, + .error = "Token is issued in future", + }, + { /* token not valid yet */ + .exp = now+500, + .iat = now, + .nbf = now+250, + .key_values = { "sub", "testuser", NULL }, + .error = "Token is not valid yet", + }, + }; + + for (size_t i = 0; i < N_ELEMENTS(test_cases); i++) T_BEGIN { + const struct test_cases *test_case = &test_cases[i]; + const char *key = NULL; + ARRAY_TYPE(oauth2_field) fields; + + t_array_init(&fields, 8); + for (const char *const *value = test_case->key_values; + *value != NULL; value++) { + if (key == NULL) { + key = *value; + } else { + struct oauth2_field *field = + array_append_space(&fields); + field->name = key; + field->value = *value; + key = NULL; + } + } + + buffer_t *tokenbuf = + create_jwt_token_fields("HS256", test_case->exp, + test_case->iat, test_case->nbf, + &fields); + sign_jwt_token_hs256(tokenbuf, hs_sign_key); + + struct oauth2_request req; + const char *error = NULL; + bool is_jwt; + + test_assert_idx(parse_jwt_token(&req, str_c(tokenbuf), + &is_jwt, &error) != 0, i); + test_assert_idx(is_jwt == TRUE, i); + if (test_case->error != NULL) { + test_assert_strcmp(test_case->error, error); + } + test_assert(error != NULL); + } T_END; + + test_end(); +} + +static void test_jwt_valid_token(void) +{ + test_begin("JWT valid token tests"); + time_t now = time(NULL); + + struct test_cases { + time_t exp; + time_t iat; + time_t nbf; + const char *key_values[20]; + } test_cases[] = { + { /* valid token */ + .exp = now + 500, + .key_values = { + "sub", "testuser", + NULL + }, + }, + { + .exp = now + 500, + .nbf = now - 500, + .iat = now - 250, + .key_values = { + "sub", "testuser", + NULL + }, + }, + { /* token issued in advance */ + .exp = now + 500, + .nbf = now - 500, + .iat = now - 3600, + .key_values = { + "sub", "testuser", + NULL, + }, + }, + }; + + for (size_t i = 0; i < N_ELEMENTS(test_cases); i++) T_BEGIN { + const struct test_cases *test_case = &test_cases[i]; + ARRAY_TYPE(oauth2_field) fields; + + t_array_init(&fields, 8); + for (unsigned int i = 0; test_case->key_values[i] != NULL; i += 2) { + struct oauth2_field *field = array_append_space(&fields); + field->name = test_case->key_values[i]; + field->value = test_case->key_values[i+1]; + } + + buffer_t *tokenbuf = + create_jwt_token_fields("HS256", test_case->exp, + test_case->iat, test_case->nbf, + &fields); + sign_jwt_token_hs256(tokenbuf, hs_sign_key); + + struct oauth2_request req; + const char *error = NULL; + bool is_jwt; + + test_assert_idx(parse_jwt_token(&req, str_c(tokenbuf), + &is_jwt, &error) == 0, i); + test_assert_idx(is_jwt == TRUE, i); + test_assert_idx(error == NULL, i); + if (error != NULL) + i_error("JWT validation error: %s", error); + } T_END; + + test_end(); +} + +static void test_jwt_dates(void) +{ + test_begin("JWT Token dates"); + + /* simple check to make sure ISO8601 dates work too */ + ARRAY_TYPE(oauth2_field) fields; + t_array_init(&fields, 8); + struct oauth2_field *field; + struct tm tm_b; + struct tm *tm; + time_t now = time(NULL); + time_t exp = now+500; + time_t nbf = now-250; + time_t iat = now-500; + + field = array_append_space(&fields); + field->name = "sub"; + field->value = "testuser"; + field = array_append_space(&fields); + field->name = "exp"; + tm = gmtime_r(&exp, &tm_b); + field->value = iso8601_date_create_tm(tm, INT_MAX); + field = array_append_space(&fields); + field->name = "nbf"; + tm = gmtime_r(&nbf, &tm_b); + field->value = iso8601_date_create_tm(tm, INT_MAX); + field = array_append_space(&fields); + field->name = "iat"; + tm = gmtime_r(&iat, &tm_b); + field->value = iso8601_date_create_tm(tm, INT_MAX); + buffer_t *tokenbuf = create_jwt_token_fields("HS256", 0, 0, 0, &fields); + sign_jwt_token_hs256(tokenbuf, hs_sign_key); + test_jwt_token(str_c(tokenbuf)); + + str_truncate(tokenbuf, 0); + base64url_encode_str("{\"alg\":\"HS256\",\"typ\":\"JWT\"}", tokenbuf); + str_append_c(tokenbuf, '.'); + base64url_encode_str(t_strdup_printf("{\"sub\":\"testuser\"," + "\"exp\":%"PRIdTIME_T"," + "\"nbf\":0,\"iat\":%"PRIdTIME_T"}", + exp, iat), + tokenbuf); + sign_jwt_token_hs256(tokenbuf, hs_sign_key); + test_jwt_token(str_c(tokenbuf)); + + test_end(); +} + +static void test_jwt_key_files(void) +{ + test_begin("JWT key id"); + /* write HMAC secrets */ + struct oauth2_request req; + bool is_jwt; + const char *error = NULL; + + buffer_t *secret = t_buffer_create(32); + void *ptr = buffer_append_space_unsafe(secret, 32); + random_fill(ptr, 32); + buffer_t *b64_key = t_base64_encode(0, SIZE_MAX, + secret->data, secret->used); + save_key_to("HS256", "first", str_c(b64_key)); + buffer_t *secret2 = t_buffer_create(32); + ptr = buffer_append_space_unsafe(secret2, 32); + random_fill(ptr, 32); + b64_key = t_base64_encode(0, SIZE_MAX, secret2->data, secret2->used); + save_key_to("HS256", "second", str_c(b64_key)); + + /* create and sign token */ + buffer_t *token_1 = create_jwt_token_kid("HS256", "first"); + buffer_t *token_2 = create_jwt_token_kid("HS256", "second"); + buffer_t *token_3 = create_jwt_token_kid("HS256", "missing"); + buffer_t *token_4 = create_jwt_token_kid("HS256", ""); + + sign_jwt_token_hs256(token_1, secret); + sign_jwt_token_hs256(token_2, secret2); + sign_jwt_token_hs256(token_3, secret); + sign_jwt_token_hs256(token_4, secret); + + test_jwt_token(str_c(token_1)); + test_jwt_token(str_c(token_2)); + + test_assert(parse_jwt_token(&req, str_c(token_3), &is_jwt, &error) != 0); + test_assert(is_jwt == TRUE); + test_assert_strcmp(error, "HS256 key 'missing' not found"); + test_assert(parse_jwt_token(&req, str_c(token_4), &is_jwt, &error) != 0); + test_assert(is_jwt == TRUE); + test_assert_strcmp(error, "'kid' field is empty"); + + test_end(); +} + +static void test_jwt_kid_escape(void) +{ + test_begin("JWT kid escape"); + /* save a token */ + buffer_t *secret = t_buffer_create(32); + void *ptr = buffer_append_space_unsafe(secret, 32); + random_fill(ptr, 32); + buffer_t *b64_key = t_base64_encode(0, SIZE_MAX, + secret->data, secret->used); + save_key_to("HS256", "hello.world%2f%25", str_c(b64_key)); + /* make a token */ + buffer_t *tokenbuf = create_jwt_token_kid("HS256", "hello.world/%"); + /* sign it */ + sign_jwt_token_hs256(tokenbuf, secret); + test_jwt_token(str_c(tokenbuf)); + test_end(); +} + +static void test_jwt_rs_token(void) +{ + const char *error; + + if (skip_dcrypt) + return; + + test_begin("JWT RSA token"); + /* write public key to file */ + oauth2_validation_key_cache_evict(key_cache, "default"); + save_key("RS256", rsa_public_key); + + buffer_t *tokenbuf = create_jwt_token("RS256"); + + /* sign token */ + buffer_t *sig = t_buffer_create(64); + struct dcrypt_private_key *key; + if (!dcrypt_key_load_private(&key, rsa_private_key, NULL, NULL, + &error) || + !dcrypt_sign(key, "sha256", DCRYPT_SIGNATURE_FORMAT_DSS, + tokenbuf->data, tokenbuf->used, sig, + DCRYPT_PADDING_RSA_PKCS1, &error)) { + i_error("dcrypt signing failed: %s", error); + lib_exit(1); + } + dcrypt_key_unref_private(&key); + + /* convert to base64 */ + buffer_append(tokenbuf, ".", 1); + base64url_encode(BASE64_ENCODE_FLAG_NO_PADDING, SIZE_MAX, + sig->data, sig->used, tokenbuf); + + test_jwt_token(str_c(tokenbuf)); + + test_end(); +} + +static void test_jwt_ps_token(void) +{ + const char *error; + + if (skip_dcrypt) + return; + + test_begin("JWT RSAPSS token"); + /* write public key to file */ + oauth2_validation_key_cache_evict(key_cache, "default"); + save_key("PS256", rsa_public_key); + + buffer_t *tokenbuf = create_jwt_token("PS256"); + + /* sign token */ + buffer_t *sig = t_buffer_create(64); + struct dcrypt_private_key *key; + if (!dcrypt_key_load_private(&key, rsa_private_key, NULL, NULL, + &error) || + !dcrypt_sign(key, "sha256", DCRYPT_SIGNATURE_FORMAT_DSS, + tokenbuf->data, tokenbuf->used, sig, + DCRYPT_PADDING_RSA_PKCS1_PSS, &error)) { + i_error("dcrypt signing failed: %s", error); + lib_exit(1); + } + dcrypt_key_unref_private(&key); + + /* convert to base64 */ + buffer_append(tokenbuf, ".", 1); + base64url_encode(BASE64_ENCODE_FLAG_NO_PADDING, SIZE_MAX, + sig->data, sig->used, tokenbuf); + + test_jwt_token(str_c(tokenbuf)); + + test_end(); +} + +static void test_jwt_ec_token(void) +{ + const char *error; + + if (skip_dcrypt) + return; + + test_begin("JWT ECDSA token"); + struct dcrypt_keypair pair; + i_zero(&pair); + if (!dcrypt_keypair_generate(&pair, DCRYPT_KEY_EC, 0, + "prime256v1", &error)) { + i_error("dcrypt keypair generate failed: %s", error); + lib_exit(1); + } + /* export public key */ + buffer_t *keybuf = t_buffer_create(256); + if (!dcrypt_key_store_public(pair.pub, DCRYPT_FORMAT_PEM, keybuf, + &error)) { + i_error("dcrypt key store failed: %s", error); + lib_exit(1); + } + oauth2_validation_key_cache_evict(key_cache, "default"); + save_key("ES256", str_c(keybuf)); + + buffer_t *tokenbuf = create_jwt_token("ES256"); + + /* sign token */ + buffer_t *sig = t_buffer_create(64); + if (!dcrypt_sign(pair.priv, "sha256", DCRYPT_SIGNATURE_FORMAT_X962, + tokenbuf->data, tokenbuf->used, sig, + DCRYPT_PADDING_DEFAULT, &error)) { + i_error("dcrypt signing failed: %s", error); + lib_exit(1); + } + dcrypt_keypair_unref(&pair); + + /* convert to base64 */ + buffer_append(tokenbuf, ".", 1); + base64url_encode(BASE64_ENCODE_FLAG_NO_PADDING, SIZE_MAX, + sig->data, sig->used, tokenbuf); + test_jwt_token(str_c(tokenbuf)); + + test_end(); +} + +static void test_do_init(void) +{ + const char *error; + struct dcrypt_settings dcrypt_set = { + .module_dir = "../lib-dcrypt/.libs", + }; + struct dict_settings dict_set = { + .base_dir = ".", + }; + + i_unlink_if_exists(".keys"); + dict_driver_register(&dict_driver_file); + if (dict_init("file:.keys", &dict_set, &keys_dict, &error) < 0) + i_fatal("dict_init(file:.keys): %s", error); + if (!dcrypt_initialize(NULL, &dcrypt_set, &error)) { + i_error("No functional dcrypt backend found - " + "skipping some tests: %s", error); + skip_dcrypt = TRUE; + } + key_cache = oauth2_validation_key_cache_init(); + + /* write HMAC secret */ + hs_sign_key =buffer_create_dynamic(default_pool, 32); + void *ptr = buffer_append_space_unsafe(hs_sign_key, 32); + random_fill(ptr, 32); + buffer_t *b64_key = t_base64_encode(0, SIZE_MAX, + hs_sign_key->data, + hs_sign_key->used); + save_key("HS256", str_c(b64_key)); +} + +static void test_do_deinit(void) +{ + dict_deinit(&keys_dict); + dict_driver_unregister(&dict_driver_file); + oauth2_validation_key_cache_deinit(&key_cache); + i_unlink(".keys"); + buffer_free(&hs_sign_key); + dcrypt_deinitialize(); +} + +int main(void) +{ + static void (*test_functions[])(void) = { + test_do_init, + test_jwt_hs_token, + test_jwt_token_escape, + test_jwt_valid_token, + test_jwt_bad_valid_token, + test_jwt_broken_token, + test_jwt_dates, + test_jwt_key_files, + test_jwt_kid_escape, + test_jwt_rs_token, + test_jwt_ps_token, + test_jwt_ec_token, + test_do_deinit, + NULL + }; + int ret; + ret = test_run(test_functions); + return ret; +} |