authentication modules for k eycloak authentication...

96
Authentication modules for Keycloak authentication server Daicy Patricia Duarte Paiva Mestrado em Segurança Informática Departamento de Ciência de Computadores 2018 Orientador Prof. Dr. Manuel Eduardo Correia, Prof. Auxiliar, DCC/FCUP

Upload: others

Post on 06-Jul-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Authentication

modules for Keycloak

authentication server

Daicy Patricia Duarte PaivaMestrado em Segurança InformáticaDepartamento de Ciência de Computadores

2018

Orientador Prof. Dr. Manuel Eduardo Correia, Prof. Auxiliar, DCC/FCUP

Page 2: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Todas as correções determinadas

pelo júri, e só essas, foram efetuadas.

O Presidente do Júri,

Porto, ______/______/_________

Page 3: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Dedicated toMy family and friends for the love and unconditional support in these years. . .

i

Page 4: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais
Page 5: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Abstract

One of the current challenges of the digital world is to guarantee the protection of the users’personal data and their identity while requesting access to a certain resource on the Internet.

Nowadays passwords are still the most used authentication method, although they are notsafe, they are still used for ease and convenience for both the user and the developer of thecontent.

When a password is easier to remember for a user, it will also be, generally, easier for anattacker to guess, while stronger passwords are increasingly difficult for a user to remember.

Currently, is very common for users to have multiple accounts, which means that they mustremember as many passwords as accounts they have, and in turn, leads them to choose weakpasswords and/or reuse them. Problem with passwords is that they are prone to be stolenthrough malicious software (keyloggers), social engineering, brute force attacks or directly byguessing since many users use special dates, names, among other personal data. In this agewhere the use of social networks is very common, the attackers’ job is made easier since usersexpose more of their life to the world through them.

Problem with passwords is which are prone to be stolen through keyloggers, social engineering,brute force, or directly by guessing since users use special dates, names, among others.

With this work, we add several alternative user authentication methods to passwords toKeycloak authentication server - methods that are more secure and friendly. In order to decreasethe number of passwords that a user must remember, and guarantee their identity throughcertificates provisioned in PKCS#11 Smart Cards (Portuguese Citizen card and IsoApplet),PKCS#12 and the possibility of using FIDO U2F security keys for authentication.

We also present an extra module that allows sending information from Keycloak to the relyingparty about the type or types of authenticators used by the user to log in. This informationwe consider important for when the current authentication is not enough to access a resourceor sensitive personal information (SPI) of the relying party, therefore the relying party couldrequest a stronger authentication based on single or multi-factors in order to achieve an evenstronger access control.

Keycloak is an open-source identity management system, developed by RedHat. It provides a

iii

Page 6: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

modular authentication server, services and access control for web applications, including supportfor standard protocols such as OpenIDConnect, OAuth 2.0 and SAML 2.0.

Furthermore, with this work, we want to present the advantages of Single Sign-On (SSO) asthe reduction of the number of passwords that the user must remember, which facilitates theway users will manage their passwords and simplify software interoperability.

iv

Page 7: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Resumo

Um dos desafios atuais do mundo digital é a garantia da proteção dos dados pessoais e daidentidade de um utilizador na altura que acedem a um determinado conteúdo na Internet.

Hoje em dia, as passwords ainda são o método de autenticação mais popular, e emborasejam considerados como um dos métodos de menor segurança, ainda são bastante usados devidoà sua simplicidade e conveniência de utilização, tanto para o utilizador como para o criadordos conteúdos. Quanto mais fácil for a password maior a probabilidade de um atacante de aadivinhar, e quanto mais forte for uma password, normalmente traduz-se numa maior dificuldadepara um utilizador a memorizar.

Atualmente, é muito comum que cada utilizador tenha múltiplas contas, o que os obriga a terde decorar várias credenciais, o que normalmente os leva a escolher senhas fracas e/ou reutilizá-las.Além disso, o problema das passwords é que são bastante vulneráveis a serem roubadas, seja apartir de software malicioso (keyloggers), através de engenharia social, de ataques de força brutaou através de tentativas com dados pessoais dos utilizadores, como datas especiais, nomes, entreoutros. Especialmente nesta altura em que a utilização de redes sociais é muito comum, o esforçode um atacante para adivinhar a senha é facilitado, já que os utilizadores começaram a expor-semais ao mundo através destas redes.

Com este trabalho, nós adicionamos vários métodos alternativos de autenticação para além daspasswords, ao servidor de autenticação Keycloak – métodos mais seguros e de utilização simples,permitindo uma redução das credenciais que um utilizador tem de memorizar, garantindo tambéma preservação da sua identidade através de certificados provisionados através de SmartcardsPKCS#11 (Cartão de Cidadão Português e IsoApplet), certificados PKCS#12 e a possibilidadeda sua autenticação através da utilização de chaves FIDO U2F.

Também foi adicionado outro módulo outro módulo que permite enviar informações doKeycloak ao cliente sobre o tipo ou tipos de autenticação usados pelo utilizador ao efetuar login,informação que consideramos importante no caso da autenticação que foi utilizada pelo utilizadornão seja suficiente para acessar a informações sensíveis ou recursos protegidos. Esta informaçãopoderá ser utilizada para permitir á relying party solicitar uma re-autenticação mais forte, atravesde um fator simple ou múltiplo factor.

O Keycloak é um sistema de gestão de identidade de código aberto, desenvolvido pela RedHat.

v

Page 8: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Este sistema disponibiliza um servidor de autenticação modular, serviços relacionados e umcontrolo de acesso para aplicações web, incluindo o suporte para protocolos conhecidos como oOpenID Connect, OAuth 2.0 e SAML 2.0.

Além disso, com este trabalho, queremos demostrar as vantagens do Single Sign-On (SSO)como a redução do número de senhas que um utilizador tem de lembrar e a maneira que simplificaa interoperabilidade do software.

vi

Page 9: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Acknowledgements

In the first place, I would like to thank my thesis advisors, Manuel Eduardo Correia for all hisunconditional support and guidance in all this research process.

I would also like to thank to the Sustain-T Program, part of the Erasmus Mundus Project forproviding me the scholarship to carry out this experience of studying abroad and their constantlysupport from the offices of Milan and Porto.

I want to thank to INESC TEC for the research scholarship to be able to continue withthis work and allow me to be part of the CRACS(Center for Research in Advanced ComputingSystems) research unit.

I am sincerely grateful to all my family, especially to my parents, my brother and Fabian forall the support, motivation and unconditional love that they offered me during these years.

Lately, I also want to specially thank Ricardo Gonçalves and João Mesquita for all their helpand useful tips during the development of this work. . .

vii

Page 10: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais
Page 11: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Contents

Abstract iii

Resumo v

Acknowledgements vii

Contents xi

List of Tables xiii

List of Figures xvi

Listings xvii

Acronyms xix

1 Introduction 1

1.1 Description of the problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

1.2 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.3 Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2 State of the Art 5

2.1 Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2.2 Authentication Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2.2.1 Password . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.2.2 X.509 Digital Certificate . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

ix

Page 12: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

2.2.3 Smart Card . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2.2.4 OTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2.2.5 Security Key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

2.2.6 FIDO2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

2.2.7 Smartphone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

2.3 Comparative . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

2.4 Authorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

2.5 Single Sign-On . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

2.5.1 SAML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

2.5.2 OAuth2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

2.5.3 OpenID Connect (OIDC) . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

2.6 Authentication Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

2.6.1 WSO2 Identity Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

2.6.2 Shibboleth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

2.6.3 Keycloak . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

2.6.4 Comparisons between the servers . . . . . . . . . . . . . . . . . . . . . . . 30

3 Design and implementation 33

3.1 Authentication Service Provider Interface (SPI) . . . . . . . . . . . . . . . . . . . 33

3.1.1 Authentication Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

3.2 Account Management Console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

3.3 Custom REST endpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

3.4 User authentication through X509 client certificate . . . . . . . . . . . . . . . . . 36

3.4.1 Keycloak configuration for mutual authentication . . . . . . . . . . . . . . 37

3.4.2 Development of the X.509 Certificate Authentication SPI . . . . . . . . . 41

3.4.3 User account interface modification . . . . . . . . . . . . . . . . . . . . . . 45

3.5 User authentication through U2F Device . . . . . . . . . . . . . . . . . . . . . . . 47

3.5.1 User account interface modification . . . . . . . . . . . . . . . . . . . . . . 50

x

Page 13: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

3.6 Custom Protocol Mapper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

3.7 Authentication Type option into login page . . . . . . . . . . . . . . . . . . . . . 53

3.8 Chapter summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

4 Testing and Results 57

4.1 Create a user and set credentials . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

4.2 Configure the authentication flow . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

4.3 Certificate X.509 provisioned in PKCS#12 . . . . . . . . . . . . . . . . . . . . . . 58

4.4 Certificate X.509 provisioned in PKCS#11 . . . . . . . . . . . . . . . . . . . . . . 60

4.4.1 IsoApplet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

4.4.2 Portuguese Citizen Card . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

4.5 U2F Security Key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

4.6 Protocol Mapper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

4.7 Chapter summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

5 Conclusion 67

5.1 Future work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

Bibliography 69

xi

Page 14: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais
Page 15: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

List of Tables

2.1 Comparative evaluation of the various similar authentication methods schemes.Adapated from [6, 35] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

xiii

Page 16: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais
Page 17: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

List of Figures

2.1 Example APDU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2.2 First Hardware Token . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

2.3 Yubico OTP flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

2.4 Yubico OTP Estructure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

2.5 U2F registration and Authentication flow . . . . . . . . . . . . . . . . . . . . . . 17

2.6 Access to SP with multiple credentials . . . . . . . . . . . . . . . . . . . . . . . . 22

2.7 SAML authentication flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

2.8 OAuth Access Token claims example . . . . . . . . . . . . . . . . . . . . . . . . . 24

2.9 OAuth process flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

2.10 OpenID Connect login example . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

2.11 ID Token example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

2.12 OpenID Connect abstract protocol flow . . . . . . . . . . . . . . . . . . . . . . . 28

2.13 Comparisons between the servers . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

3.1 Authenticator SPI class structure . . . . . . . . . . . . . . . . . . . . . . . . . . 34

3.2 Keycloak Authentication Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

3.3 SSL Handshake for mutual authentication . . . . . . . . . . . . . . . . . . . . . . 37

3.4 KeystoreUtil Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

3.5 rootCA certificate configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

3.6 Server certificate configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

3.7 Keycloak class overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

xv

Page 18: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

3.8 X509 Client Certificate Authenticator classes overview . . . . . . . . . . . . . . . 43

3.9 X509 Certificate Authenticator Configuration . . . . . . . . . . . . . . . . . . . . 44

3.10 Get Information from user certificate . . . . . . . . . . . . . . . . . . . . . . . . . 45

3.11 X509 Cert template information exchange . . . . . . . . . . . . . . . . . . . . . . 46

3.12 X509 Certificate template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

3.13 X509 Certificate from Portuguese Citizen Card . . . . . . . . . . . . . . . . . . . 46

3.14 X509 Certificate template SC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

3.15 U2F Registration Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

3.16 U2F Authentication Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

3.17 U2F ajax information exchange . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

3.18 FIDO U2F Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

3.19 Keycloak Protocol Mapper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

3.20 Authenticator Protocol Mapper graphical interface . . . . . . . . . . . . . . . . . 53

3.21 Authentication configuration for Authenticator Selector . . . . . . . . . . . . . . 54

3.22 Authenticator Selector page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

4.1 Keycloak - Create a user . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

4.2 Keycloak - Authentication flow configuration . . . . . . . . . . . . . . . . . . . . 59

4.3 User account - Config X.509 Certificate(PKCS12) . . . . . . . . . . . . . . . . . . 59

4.4 Protocol Mapper Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

4.5 Protocol Mapper Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

4.6 Client certificate information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

4.7 U2F Register request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

4.8 U2F touch device request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

4.9 User account - U2F Register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

4.10 U2F Authentication information into token claim . . . . . . . . . . . . . . . . . 64

xvi

Page 19: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Listings

3.1 Standalone.xml file configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . 383.2 Wildfly HTTPS Listener Configuration . . . . . . . . . . . . . . . . . . . . . . . . 393.4 U2F Start Registration function output . . . . . . . . . . . . . . . . . . . . . . . 493.5 U2F Finish Registration function output . . . . . . . . . . . . . . . . . . . . . . . 493.6 U2F Start Signature function output . . . . . . . . . . . . . . . . . . . . . . . . . 503.7 ProviderConfigurationBuilder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523.3 X509 Certificate authenticator configuration options . . . . . . . . . . . . . . . . 56

xvii

Page 20: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais
Page 21: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Acronyms

2FA Two-Factor authentication

3FA Three-Factor authentication

4FA Four-factor authentication

5FA Five-factor authentication

AAL Authenticator Assurance Level

APDU Application Protocol Data Unit

AWS Amazon Web Server

CA Certification Authority

CORS Cross-origin resource sharing

CRL Certificate Revocation List

CSR Certificate Signing Request

CSRF Cross-site request forgery

FIDO Fast IDentity Online

HTTPS Hyper Text Transfer Protocol Secure

JOSE JSON Object Signing and Encryptionstandards

JSON JavaScript Object Notation

JKS Java Key Store

JWT JSON Web Token

MFA Multi-Factor authentication

NIST National Institute of Standards andTechnology

OASIS Organization for the Advancement ofStructured Information Standards

OP OpenID Provider

OIDC OpenID Connect

OTP One Time Password

PII Personally Identifiable Information

PIN Personal Identification Number

PKCS Public key Cryptography Standards

PKI Public Key Infrastructure

REST Representational State Transfer

SAML Security Assertion Markup Language

SFA Single-Factor authentication

SMS Short Message Service

SSO Single Sign-On

SSL Secure Sockets Layer

SPI Service Provider Interface

SP Service Provider

TOTP Time-based One-Time Password

TLS Transport Layer Security

UIT-T International TelecommunicationsUnion

URI Uniform Resource Identifier

URL Uniform Resource Locator

USA United States of America

U2F Universal 2nd Factor

xix

Page 22: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais
Page 23: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Chapter 1

Introduction

Despite technological advances, the user remains the weakest link in Internet security. Pass-words(something user knows) continue to be the authentication method most used today [6],and therefore the consensus among researchers is that something more secure and user-friendlyis necessary. Nonetheless, they generally recommend strict password creation policies (such asalphanumeric characters, use of capital letters, length requirements and mandatory digits), whichdoes not reduce the damage but increases the frequency on which the same passwords will bereused - since a stronger password becomes hard to remember). A study carreid aout by Adams[1] showed that when users are forced to comply with strict password creation policies, makingthe user experience annoying and uncomfortable,thus the tendency is non-compliance with therules by any means possible.

The evolution of technology (Internet nearing a worldwide reach, easier accessibility to mobiledevices, the increased usage of cloud-based applications and most recently the considerableexpansion of the Internet of Things (IoT)), have increased the number of services used by peoplein the Internet, thus, increasing the number of accounts they need to manage. Besides theadvantages offered to the user, such as speed, comfort, among others, it also heightens theirexposure to more threats and vulnerabilities. Given the drastic increase of Personally IdentifiableInformation (PII) leaked on the internet in recent, users should be concerned about personaltheir credentials and how to perform authentication on different platforms securely.

Millions of PII data have been compromised, not only small companies have fallen victim ofsuch practices but also large corporations, e.g.: In 2013, Adobe[5] suffered a data breach whichleads to the exposure of personal information from 2.9 million users on the internet, along withtheir credit card details. In 2018 alone, the data from Reddit users[58], T-mobile[30, 69] andseveral hospitals across the globe have been compromised because of vulnerable authenticationmechanisms. Despite all these incidents, stubborn practices are still very frequently seen in newwebsites and services introduced to the Internet.

In this year’s Data Breach Investigations Report[73], among the top 20 action varietiesin breaches, it is clear that one of the main causes that lead to data exfiltration was stolen

1

Page 24: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

2 Chapter 1. Introduction

credentials, which occupies the first place, followed by phishing on the third place. This enforcesthe theory that to safeguard sensitive data and the need for stronger authentication measuresimplementation.

Over the years researchers have been warning about the reality that passwords alone are notenough to warrant sufficient protection and emphasizing the need of Multi-Factor Authentication(MFA) solutions. Two-factor Authentication (2FA), has become one of the most acceptedverification tools. One of the most used methods nowadays is SMS-Based OTP, but SMS is nolonger considered to be safe, and the National Institute of Standards and Technology (NIST)started to discourage its use [20, 21].

The main goal of information security practices is to keep information out of unauthorizedhands and protect it against unapproved modifications. At the moment, the hardware-basedauthentication as a second factor is a good alternative for these challenges - Google decidedto opt for this alternative granting security keys to all its employees, and as a result, phishinghas not happened ever since[29, 39, 83]. However, is its widely known that this solution is notpreferred among a certain group of users, which suggests that this has no relation to the lack oftechnical functionality[48].

Our aim is to raise awareness of the problems derived from choosing a weak password andit’s ongoing reusage, as well as present alternative authentication methods to plan passwords,using tools that will provide an additional layer of security, such as two-factor authenticationapproach as well as the advantage of adopting authentication standards such as Single Sign-On(SSO) which will simplify software interoperability (even if the software was manufactured by adifferent vendor), achieving a better and safer user experience.

1.1 Description of the problem

Nowadays, passwords are the predominant authentication mechanism for information systemsand as an aggravating factor, it is known that people have difficulty remembering password thatare considered secure [63]. If the user has multiple accounts, which is largely common, he/shemust remember several passwords, which frequently makes the user choose a weaker passwordsor reuse the same password on different services [74].Consequently, it can be damaging for theusers as they could end up being deceived to log in to a malicious service and thus revealingpasswords which are potentially used in other platforms. In case an attacker discovers the reusedpassword, they will have been granted access to multiple accounts. Through an extension in theuser browser’s, studies [15, 19] have observed the habits of thousands of users and the conclusionwas that on average, an individual user has managed 25 accounts with 6 unique passwords andin most cases, users ended up forgetting the passwords for most platforms. In addition, the studyrevealed that users have accounts which they do not remember having registered for.

Users, even knowing that a password is weak or insecure, are still motivated by these badpractices because they do not see immediate negative consequences for them[11, 70]. Even if the

Page 25: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

1.2. Objectives 3

organization has a password policy, users do not follow the passwords tips, because the benefitsare few or smaller for them considering the cost of following these guidelines. An example ofthis problem is in the case of the banks where the victims of fraud receive a refund when anattacker steals from their account in the case of stolen credentials[11], making the attack almostinnocuous to the user.

Other studies[70] show that users prefer comfort over safety. Comfort means more than easeof use for the individual user, but also ease of use for their trusted friends or family members(users are willing to share their passwords with the people they trust) ). Also, if the user forgetsthe password the process of recovery is fairly easy. The password fatigue (stress for having toremember many passwords) is another reason that leads the user to choose weak passwords orreuse them in different platforms.

It is also necessary to emphasize that many users still have no conception of password crackingor social engineering, and underestimate the probability of the existence of an attacker sitting atthe keyboard trying things manually [18]. To further show the users’ naivety regarding passwords,according to the splashData report [71], "123456" and "password" are the most common passwordsused today.

1.2 Objectives

The main goals is to define and implement new authentication modules on keycloak authenticationserver. We identified the following main objectives

• Define which authentication methods will be implemented.

• Research the current state of the art of the authentication methods that will be imple-mented and tools that already implement these authentication methods.

• Define the authentication server to be used.

• Study the architecture of the server authentication to add new authentication providersmodules.

• Implement the proposed authentication providers modules.

• Send information to the client about the authentication type used by the user to log in.

• Process the required authentication type sent by the Relying Party for user re-authentication.

• Deployment of the system in real scenarios.

• Proof of concept integrate the modules in a real web application.

Page 26: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

4 Chapter 1. Introduction

1.3 Outline

Here a summary of the chapters of the dissertation and what will be discussed in each of them:

• Chapter 2 State of the Art, we will present important concepts necessary for this work,and what is the current status in the field of study and details of authentication methodsin current systems.

• Chapter 3 Design and implementation, we describe detail of the architecture andimplementation of the authentication modules developed

• Chapter 4 Testing and Results, we will talk about tests performed on the authenticationmodules and the authenticator type mapper developed and the current achievements.

• Chapter 5 Conclusion and Future Work, discussion about the main findings of thiswork, also unsolved problems, current limitations, and the future work.

Page 27: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Chapter 2

State of the Art

2.1 Authentication

Authentication is the process of determining whether a user (or other entity) should have accessto a system[67]. Nevertheless, an authenticated user generally does not receive access to allsystem resources; it depends on the privilege granted to the user, the user only can access tosystem modules for which is authorized. Authentication is the security process that confirmsthat a user’s identity is authentic, which allows the service to know who is talking to.

The National Institute of Standards and Technology (NIST), is responsible for the developmentof information security guidelines. The Special Publication 800-63B [21] guidelines describethree levels of Authenticator Assurance Levels (AAL). Additionally, provides technicalrequirements for each of these levels in order to provide some confidence in the authenticationprovided by Identity Provider(IdP) to a Relying Party(RP).

In the same publication, NIST.SP.800-63B [21], is defined as an authenticator (defined astoken in the previous version) as something that the claimant possesses and controls (typically acryptographic module or password) that is used to authenticate the claimant’s Digital Identity.Below are the three levels, which are taken into account to measure how reliable the authenticationis:

• AAL1: Provides some assurance, require at least one authentication of a factor.

• AAL2: Provides high confidence that the claimant controls the authenticator(s) linkedto the subscriber’s account. Requires two different authentication factors and approvedcryptographic techniques are required.

• AAL3: Provides very high confidence that the claimant controls the authenticators linkedto the subscriber’s account, based on the proof of possession of a key through cryptographicprotocols. Requires hardware-based authenticator and an authenticator that providesverifier impersonation resistance are required.

5

Page 28: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

6 Chapter 2. State of the Art

2.2 Authentication Methods

Authentication methods should be as safe as possible. They serve to answer the question: "Areyou who you say you are?". Humans can be authenticated based on something they know,something they have or something they are [67]. The way in which someone can be authenticatedis called factors.

• Something the user knows: knowledge factor, such as password, PIN and secret question.

• Something the user has: possession factor, such as smartcard, smartphone, security keys.

• Something the user is: inherence factor, in this category, are biometrics, e.g.: fingerprint,iris recognition, voice recognition, facial recognition.

Users can be authenticated using one of these categories or in combination with one or morecategories. Single-Factor authentication (SFA) happens when only one of them is used, andMulti-Factor authentication (MFA) uses combinations of factors to provide extra security layers.However, we are not saying that we cannot have a strong authentication without MFA, SFAshould not be necessarily weak, such as the case of biometrics.

Next, we define the types of authentication factors.

Single-Factor authentication (SFA), only a single category of credentials is required to identifythe party requesting access, typically a password or a Personal Identification Number (PIN).

Multi-Factor authentication (MFA), more than one category is required. The goal of MFA isto provide several security layers instead of just one.

Two-Factor authentication (2FA) generally refers to the verification in two steps. It is thesecurity verification process where the user provides two means of identification (two-factors) toprove their identity, which makes it safer than having just a single factor. In most cases, one offactors is something that user knows, such a password and another something that user has sucha security key. It is necessary to indicate that to be considered two factors must be differentcategories, e.g., passwords in combination with a shared secret correspond to the same categorysomething that the user knows therefore they remain SFA. 2FA increases the password-basedauthentication security, by requiring a hardware device as a proof of possession, additionally, tothe knowledge of the password. In this case, this hardware device is used as second-factor. Evenif a password is stolen, still the hardware device still is necessary to log in.

The two-factor authentication is nowadays the most common way of adding an extraverification to protect the authentication process. In practice, the SMS-Based two-factorauthentication is widely adopted, but it is not safe. An attacker can obtain the One TimePassword (OTP) that is sent via Short Message Service (SMS) and forward it to his mobile [21],for this reason, many companies are leaving use as a factor of authentication. Yet, the reason for

Page 29: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

2.2. Authentication Methods 7

this type of method still being used is due to the fact that most people in the first world countriespossess a mobile device, especially a cell phone or a smartphone, making the introduction ofthis type of method quite easy, and avoids the problem of the distribution and costs of specifichardware-based tokens.

As alternatives to the previous method, there are more secure methods, such as time-basedOTP, which are generated by applications, i.e., based on software, e.g., Google Authenticator andAuthy. Basically, run on the mobile phone generating codes of 6 or 8 digits that change while afew seconds. A different solution for 2FA is a hardware-based authentication such as YubiKeys.

Three-Factor authentication (3FA), involves a combination all three main categories.

When talking about Four-factor authentication (4FA), this involves the location factor, andFive-factor authentication (5FA) involves time factor. Although sometimes, time is used insteadof location as 4FA. Such is the case of banks, which they use to prevent fraud, for example, if acredit card has been used (physically) in Europe and 20 minutes later in China or the UnitedStates of America (USA), it raises an alarm to inform of a possible crime.

2.2.1 Password

Password is the most common authentication method today. It is a string of characters, andusually used in conjunction with a username. The term "password" is also associated withpassphrase, passcode, and passkey. The passphrase is a combination of characters but easy toremember by users, e.g., a sentence of a song. The last two are passwords only contains numbersan example is the PIN.

An ideal password is something that you know, something that a computer can verify thatyou know, and something nobody else can guess[67]. However, the problem with passwords isthat they are not always secret. Nowadays users typically manage several accounts with theneed of having a password for each account, thus they prefer to choose passwords that are easyto remember. When creating passwords, people often use information that is meaningful andimportant to them [11, 68, 74], probably the family name, mother, father, son name, date ofBirthdays, among others. Easy-to-remember passwords are also easy to guess. Many times, usersprefer to have their passwords written in post-it notes.

According to splashData report[71] among the top of the most used passwords in 2017 stillare "123456" and "password", in this year "starwars" was added to the list, probably due to therelease of a new movie of the top-rated Star Wars franchise. Accounts protected with thesepasswords can easily be compromised with a dictionary attack.

The difficulty of remembering passwords has been studied since doing some time [44] andresearchers have been able to guess 75% of the countersigns of users, others have been compromisedwith dictionary attacks. Passwords are a scheme purely based on memory and must be enteredmanually at the time to log in, so they are also vulnerable to observation, among others such as

Page 30: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

8 Chapter 2. State of the Art

phishing attacks, keyloggers, social engineering or merely guess them.

Among the main advantages of passwords in comparison to other authentication methodsare that they can quickly be re-established in case of loss. The ease of implementation, besidesthat, does not constitute any monetary cost for the user or for those who offer a web service, incomparison, for example, with smart cards or security key. They are easy to learn and use dueto years of user experience.

2.2.1.1 Encrypted Password managers

Nowadays, web browsers allow users to save their passwords, sometimes with the option toencrypt them with a master password and sync functionalities that store the passwords in thecloud, allowing the user to access them anywhere by just log in in the browser. The datasynchronization services of Firefox (Firefox Sync), Opera (Opera Link) and Google Chrome(Google account) encrypts all the information stored in the servers on the client side, so theyare considered safe. Saving passwords in the web browser provide comfort to the user since alltheir accounts passwords can be stored in one place, and it is not necessary to re-enter each timewhen the site is visited. However, it is not advisable to synchronize or store the password in acomputer that is not for personal use, for example in a cybercafe, since people with minimalknowledge can have access to all the passwords stored in the browser. Usually to be able to seeall the passwords stored in the browser do not require any authentication. Anyone who has accessto the user’s browser will have access to all stored passwords. Losing the master password meansto reset the master password, with this action all saved username and passwords are removed.

LastPass [36], is a free password manager, available for phones, tablets and desktop computersfor all major operating systems and browsers. Besides, there are also paid versions. It works asfollows, passwords are stored on the LastPass server and are protected by a master password.Additionally, allows synchronisation between browsers. The user can choose the master password,but the program allows to generate safe and random passwords, which is a better option, becauseif the password is weak, an attacker can easily access to the master password, which is a betteroption avoiding the problems like the password reuse or choosing common words because if thepassword is weak, an attacker can easily access to the master password.

In March 2017, on the LastPass blog [38], a researcher reported two vulnerabilities weremitigated. The vulnerability consisted in first an attacker would first lure a user to a maliciouswebsite. Once on a malicious website, an attacker could make calls to LastPass APIs, or in somecases run arbitrary code, which allowed the attacker to retrieve and expose information fromthe LastPass account, such as the user’s login credentials. However, they indicate that sensitivepersonal information (SPI) was not stolen or compromised, and said that it was not necessaryto change the master password. While in May 2011 [37], a suspicion was generated that thedatabase of the encrypted password was being downloaded including the server salt and theirsalted password hashes.

Page 31: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

2.2. Authentication Methods 9

Out of these incidents, LastPass is as accessible as passwords, that is, anyone who can usea password can also use LastPass. It is necessary to install a plug-in to use with the browser.Losing the master password is irreversible, but there is an account recovery facility based on alocally stored onetime password [6].

2.2.2 X.509 Digital Certificate

A digital certificate is a digital credential that provides information about the identity of anentity, usually contains the user’s public key, as well as other information [42].

Digital certificates allow entities to trust each other. Different areas use these infrastructuresin their applications and also for communication between different entities (such as users,institutions, processes or devices) to ensure confidentiality, integrity, authenticity, and non-repudiation. Certificates can be used in interconnected systems (they are particularly usefulfor this), for applications where a large number of entities exists and even entities associated todifferent institutions unknown to each other have to authenticate and communicate securely [76].

The certificates are generated and issued by a trustworthy authority called the CertificationAuthority (CA). This authority guarantees the validity of the information contained in thecertificate for a period of time [42],

In some circumstances, however, its validity must end before the assigned date, that is, itmust be revoked, a Certificate Revocation List (CRL) is necessary. An example of a reason for arevocation is if a user’s certificate is stolen or lost. A CRL contains a list of revoked certificate serialnumbers together with another information such as revocation date and additional extensionswhich contain more details about the revoked certificates and the revocation reasons [76].

The term X.509 is based on the X.509 standard defined by the International Telecommunica-tions Union UIT-T organization for Public Key Infrastructure (PKI).

Version 3 of X.509 certificates is the one that is currently used, was standardized in 1996 andis compatible with previous versions, it has the following attributes, according to [9].

• versión: Version of the X.509 certificate.

• serialNumber: Unique number attributed by CA.

• signature: Structure that identifies the algorithm used to generate a CA signature thataccompanies the certificate.

• validity: Structure with two dates that delimit the period of validity of the certificate,start/end date and time.

• subjectPublicKeyInfo: Structure containing the public key of the certificate holder andidentification of the corresponding algorithm.

Page 32: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

10 Chapter 2. State of the Art

• issuer e subject: Identify the CA and the certificate holder respectively. Both are of thetype Name.

• extension: (optional)

Digital certificates or public key certificates are used to solve the problem of a man-in-the-middleattack, while the public key encryption can only ensure that a message is not disclosed by athird party.

2.2.3 Smart Card

As an alternative to paper and cardboard cards, plastic cards were created that were more robustand durable for daily use. In the early 1950s Diners Club introduced the first credit card forpayment applications. Later, with the entry of Visa and MasterCard into the field led to avery rapid proliferation of plastic money in the form of credit cards. First, the functions ofthese cards were quite simple, but with the increasing proliferation of card use, these ratherrudimentary functions and security technology were no longer adequate, principally since threatsfrom organized criminals were growing apace[24, 56]. Magnetic cards are predecessors of smartcards and store information in a magnetic strip that they have adhered on the surface.

The smart card is a secure, tamper-resistant device, are credit card-size, plastic cards thathold an embedded computer chip containing an operating system, programs, and data. The datastored on the card can be secured with a secret (usually a password), which is shared betweenthe cardholder and the smart card. Only the person knowing the secret can use the card andthe information stored on it. Additionally, smart cards can execute programs and commandsand become able to encrypt and decrypt information[24]. Portability and security are the twoadvantages to use smart cards. Also, one of the main characteristics of the smart card unlikemagnetic cards is that the data stored in it can not be copied, they are easy to use and havebeen around for a long time. They are currently widely used as citizen identification, as creditcards, to store information or to access control to buildings.

Smart cards are into "something the user has" category, but one of the main disadvantages isthat to use is necessary a smart card reader and/or to install software. They can be classifiedupon different criteria:

• Type and features to the microchip: Memory card or Microprocessor card. Memory card canonly store data and have no processing power for data management. Microprocessor cardis equipped with an embedded Integrated Circuit(IC) chip, and card OS, what allows haveon-card dynamic data processing capabilities and different functions like install applicationson the card.

• Type of connecting interface: Contact card, Contactless card (equipped with antenna), andDual Interface (equipped with both, contacts and antenna).

Page 33: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

2.2. Authentication Methods 11

2.2.3.1 Security related standard

• PKCS, Public-Key Cryptography Standards are a series of standards initiated by RSA tofoster interoperability of cryptographic systems [24].

• PKCS#11 - Cryptographic Token Interface Standard: Defines an Application ProgrammingInterface(API) called Cryptoki, for cryptographic devices, which hold cryptographicinformation and perform cryptographic functions.

• PKCS#15 - Cryptographic-Token Information Format Standard: intended to standardizethe use of cryptographic tokens to identify themselves to multiple, standard-aware applica-tions regardless of the application’s cryptographic token interface provider. The centralissue in such cases is the interoperability among components running on different platforms.

• Java card is a smart card that has the capability of running Java programs using a restrictedcommand set and library on-card[24].

2.2.3.2 Command APDU

Application Protocol Data Unit (APDU), commonly called APDU, is the basic unit regarding allcommunication with the microchip. All communication with the smart card is through APDUcommands, which means that when sending an APDU command we will receive an responseAPDU. The ISO/IEC 7816 standards define the structure of an APDU.

A command APDU consists of four bytes designated as follows: Class(CLA), Instruction(INS),Parameter 1(P1), Parameter 2(P2), Length of the command(LC), Command DATA, Length ofexpected(LE) (see figure 2.1).

INSCLA P2 DATAP1 LELC

DATA SW1 SW2

a)

b)

Figure 2.1: Example a) Command APDU, b) Response APDU

2.2.3.3 Response APDU

Response from the microchip after a command is codified, in others words, it is the reply of acommand APDU, an optional data field composes it and the status word. The status wordsare two mandatory bytes(SW1 and SW2), see figure 2.1 (b). When SW1=0x90 and SW2=0x00indicate a successful command. In the ISO 7816 standard, all status codes are defined, i.e.,possible values of SW1 and SW2.

Page 34: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

12 Chapter 2. State of the Art

2.2.3.4 IsoApplet

An applet is a small program that can be downloaded and executed on a client. The term appletis used for programs running on Java Cards. A Java application that is stored and executed on aJava Card is called card applet. IsoApplet[75] is a Java Card PKI applet aiming for ISO 7816compliance, open-source capable of saving a PKCS#15 file structure and perform PKI relatedoperations using the private key together with OpenSC, such as signing or decrypting. Privatekeys can be generated directly on the smartcard or imported from the host computer. The appletsupports RSA 2048 bit with on-card key generation.

2.2.3.5 OpenSC

OpenSC [78] an open-source smart card tool and middleware, provides a set of libraries andutilities to work with smart cards, focusing on smart cards that support cryptographic operations.OpenSC implements the PKCS#15 standard and the PKCS#11 API.

2.2.3.6 POReID

POReID [41], is a Java component to interact with the Portuguese Citizen Card, developed usingthe API Java Smart Card I/O, provides methods that facilitate operations such as obtainingpublic data of the citizen card, as well as protected data with a PIN as the case of the address.

2.2.4 OTP

OTP, it is one of the simplest and most popular forms of two-factor authentication. As the nameimplies, it is a password of single-use, that is, they are only valid only for one authenticationrequest. The OTP provides one more security layer to the authentication step. There arehardware and software capable of generating OTP.

The idea of an OTP was suggested by Leslie Lamport[34], were central importance is theshared secret (frequently called by “seed”), as an essential basis for calculating the OTP, butone disadvantage is the high computation cost.

The one-time password systems are designed to counteract the replay attack, but not prevent anetwork eavesdropper from gaining access to private information and does not provide protectionagainst either "social engineering" or active attacks [23].The most common way to use OTP assecond-factor is sending it via SMS to mobile phone. Implemented in this way is still vulnerableto phishing [35].

Page 35: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

2.2. Authentication Methods 13

2.2.4.1 Main methods to generate OTP

• HOTP, based on Hashed Message Authentication Code (HMAC) [45, 46], it is an algorithmthat generates a pseudo-random sequence of codes based on an increment counter.

It is older and less secure than Time-based One-Time Password (TOTP). The reason whyit is less secure than TOTP is that it is event-based, which means that the OTP doesnot expire until it is newly generated. In this case, the counter will be incremented, andthe next password should be different, which is quite dangerous if an attacker obtains thepassword generated a month ago, it could use it at any time, this is why HOTP is not thesafest way to implement OTP.

• TOTP, an extension of HOTP to support time [46]. It is time-based OTP, which meansthat the passcode is getting generated every certain time, in others words, provides short-lived OTP values, they are valid only for a specific number of seconds. In case the TOTPcode is compromised, it can be used only during the specified period. When the period iscompleted, it will no longer be valid.

The algorithm that generates the passcode uses the current time of the day as one of it isfactors instead of the incremental counter used in the HOTP, ensuring that the passwordis unique.

Nowadays, there are several methods to delivering OTP

• SMS Based OTP, already discussed previously, where the passcode is sent as a conventionaltext message, without the need of a special application. However, because of the series ofvulnerabilities, SMS is not considered safe, and NIST is discouraging its use [20, 21]. Weexplain in more detail in the section 2.2.7.1.

• Software token, through applications like Google Authenticator, FreeOTP or Authy, thatdisplay the OTP code. The code must be manually entered in the log in form.

• Security key, like Yubikey devices 2.2.5.1, it needs to be plug-in into the USB port, and itautomatically types the OTP code in the log in form.

• Others, like paper, phone calls.

2.2.5 Security Key

Using hardware tokens are becoming very popular nowadays, as a reliable and secure alternativeto the password. It is a small integrated device which makes it convenient for people to carry.The first hardware token was a device with a screen where the token generated and displayed acertain period of time, like SecurID and later Digipass, see figure 2.2, These solutions are nolonger trusted because if the seed is leaked the codes become easy to predict. One example wasthe database leak suffered by SecurID in 2011, which allowed cloning the SecurID tokens [72].

Page 36: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

14 Chapter 2. State of the Art

Figure 2.2: Security Token Digipass and SecurID

Security keys are a hardware device which allows authenticating the user, some like OTPYubikey or U2F forced to submit a proof of possession, by pressing a button. The button tapprovides a small electrical charge that activates the key, in others words authorize any operation(register or authenticate).

Security Keys are second-factor devices that protect users against phishing and man-in-the-middle attacks, usually connected to the USB port, but they can also be connected viaNFC, Bluetooth, etc. The Security Key design has been standardized by the FIDO Alliance, anorganization with more than 250 member companies spanning the industry [35], they are in thecategory "something the user has", in the following subsection, we are going to focus first on theOTP YubiKeys and then on the Universal 2nd Factor (U2F) devices.

2.2.5.1 OTP YubiKeys

A YubiKey is a small device manufactured by Yubico, capable of "typing" unique OTPstriggered by a button touch [84], designed to authenticate a user in network-based services[33] issomething the user has that provides security protection beyond something the user knows (likea username/password). In order to be usable out-of-the-box, no driver required or necessary,just plug in computer’s USB port and it identifies itself as a keyboard, in others words, it actslike a USB keyboard. It should not be used as a single factor, in the case that someone gets youryubikey and also knows your username, would be able to access into your accounts associatedwith the device.

The Yubikeys can be configured to work in the following modes [84]:

• Yubikey OTP, 128 bits AES-128 encrypted information encoded into 32 ModHex characters,method typically employed.

• OATH-HOTP, the OTP is generated using the standard RFC 4226 HOTP algorithm, theHOTP output can be truncated to 6 or 8 digits.

• Challenge-response mode, a client-side API interface is used to retrieve the OTP, the OTPis not typing in the login form manually, the calulated OTP is read via an API call, thatis, the interaction is automatically.

Page 37: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

2.2. Authentication Methods 15

• Static mode, the output is a 38-character static password instead of OTP.

In this section we will focus in OTP only, it is a 44-character, 22 bytes information in ModifiedHexadecimal (ModHex) encoding, one use, 128-bit encrypted Public ID and Password, where thefirst 12-character (6 bytes) represent the Public ID (also called Yubikey ID), used to associate thedevice with user accounts, and the rest 32-character (16 bytes) is a unique passcode, is generatedeach time the button is pressed [84], see figure 2.3. The reason for used ModHex encoding isthat it is easy to map characters within the scancode, and the result is a password that willwork between different keyboard layout, but the 16 characters available in the ModHex alphabetmakes the password look unsafe, what really provides security is the length of the password andthe randomness with which it is generated. The MaxHex alphabet was created by Yubico andthe 16 character used are: c,b,d,e,f,g,h,I,j,k,l,n,r,t,u,v [84].

Figure 2.3: Yubico OTP flow [80]

OTP is generated in base on an encryption secret value, random values, counters. First the32 character (16 bytes) plaintext are encrypted using AES-128 key unique in each Yubikey, thenprepends the encrypted 16 bytes token with a 6 bytes plaintext public ID that does not changeand that is used as part of the OTP verification and finally, the sequence will be encoded usingModHex algorithm. The 16 bytes OTP passcode contain the follows information [33, 52, 84] (figure 2.4):

• Private ID (uid), it is the unique device ID (6 bytes), which is assigned when a Yubikey isprogrammed.

• Usage counter (useCtr), is a non-volatile counter (2 bytes), for Yubikey 2 this bit is alwayszero. This counter is used by Yubikey 1 to indicate that the trigger was not initiated bythe integrated button, but by an external trigger.

Page 38: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

16 Chapter 2. State of the Art

• Timestamp (tstp), initialized with random data (3 bytes) on startup, after that theincrement by an 8Hz internal clock, it is stored in volatile memory during each session,when it reaches its limit, the session is terminated.

• Session usage counter (sessionCtr), the counter starts at zero and is incremented wheneverthe device is plugged in (1 byte).

• Random number (rnd), are 2 bytes pseudo-random numbers that is supposed to addentropy.

• CRC-16 Checksum (crc), is supposed to detect transmission errors. This checksum is usedfor data-integrity checking, but does not provide cryptographic integrity. If the checksumis valid, the OTP is validated otherwise it is rejected.

A sample output from a YubiKey, generated tree times may look like:

fifjgjgkhchbirdrfdnlnghhfgrtnnlgedjlftrbdeutfifjgjgkhchbgefdkbbditfjrlniggevfhenublfnrevfifjgjgkhchblechfkfhiiuunbtnvgihdfiktncvlhck

fifjgjgkhchb irdrfdnlnghh fgrt nnlged jl ftrb deutuid SessionCtrtstpuseCtr rnd crcPublic ID

Figure 2.4: Yubico OTP Estructure

To verify the OTP, it is necessary to revert the steps, the server-side software, e.g., theopen-source validation server provided by Yubico, follows the following steps: first decode theModHex and remove (split) the Yubikey ID, identify the Yubikey by the public ID and retrievethe corresponding AES key, then decipher the following 32 characters corresponding to the OTPwith the corresponding AES key, and validate the resulting data validating the CRC checkusmand comparing the counters if they correspond to the values previously saved.

2.2.5.2 U2F Security Key

The Universal 2nd Factor (U2F) is a challenge-response protocol, was created by Google andYubico, with contribution from NXP, and is today hosted by the open-authentication industryconsortium Fast IDentity Online (FIDO) Alliance[81], allows online services to increase thesecurity of their existing password infrastructure by adding a strong cryptographic second factorto user login[35, 66]. The user logs in for example using username and password as before,and then authenticate by the U2F device, see the sequence diagram in figure 2.5. NowadaysFacebook, Gmail, Dropbox, GitHub, Salesforce.com, the UK government, and many more adoptU2F security key, but at time Chrome, Mozilla Firefox and Opera are the browsers supporting

Page 39: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

2.2. Authentication Methods 17

U2F, while Microsoft is working to support in the future and Apple has no official plans tosupport it in Safari [29, 82].

U2F devices, unlike OTP Yubikeys, generate asymmetric keys, that is, they use public keycryptography, and only the public key is stored in the service, while private key is registeredin the device. According to [35, 66], using public key cryptography this device protects againstman-in-the-middle, phishing, session hijacking, and malware attacks.

When using the U2F device we have 2 flows, register to create the key pair andauthenticate to generate signature.

• Register, the user authenticates with the first factor. The registration page of the deviceis displayed, through which the register function, responsible for creating the key pair iscalled, the user needs to authorize the operation (to create the key pair) by touching thedevice, creating a unique key pair for the local device. Finally, the server associates thepublic key to the user account.

• Authenticate, like the first phase of registration, using the first factor, and with the pressingof the U2F’s button, the device uses its private key to sign the challenge sent by the serverand return the answer, allowing the service to verify the authenticity of the user, using thepublic key stored in the registration.

Username

Figure 2.5: U2F registration and Authentication flow

According to [29] Google delivered YubiKeys that supporting U2F protocol to its employeesin early 2017 in place of passwords and one-time codes like Google Authenticator (an applicationdeveloped by them), to avoid phishing attacks with very positive results, with no phishingincident reported since the adoption of U2F.

2.2.6 FIDO2

FIDO2 is the passwordless evolution of the FIDO U2F standard, created by Yubico andGoogle, it is a combination of W3C Web Authentication specification (WebAuthn API) that

Page 40: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

18 Chapter 2. State of the Art

allows developers to integrate FIDO authentication into web browsers, and FIDO’s Client toAuthenticator Protocol(CTAP) that allows users can log in without a password. CTAP is anapplication layer protocol used for communication between a client (browser) or a platform(operating system) with an external authenticator such as a mobile phone or hardware device,over USB, Bluetooth or NFC[14, 79].

FIDO2 is built on the same security and privacy features of FIDO U2F, while with U2F theuser has to enter their username and passwords, FIDO2 only requires possession of the securitykey to log in as single-factor.

2.2.7 Smartphone

2.2.7.1 SMS Based OTP

SMS Based OTP, are commonly used as an additional factor in a multi-factor authentication andauthorization for many different applications, the basic idea is to send the OTP as SMS messagesto the user’s mobile phone, which the user must then transcribe into the site’s log in page. Butcannot be considered safe for the fact to the series of attacks suffered[47], Reddit announcedin August 2018 an incident where main attack was via SMS intercept [31, 58]. "Because ofthe risks, we are discouraging the use of SMS as an “out of band authenticator" said by PaulGrassi in NIST blog [20]. Another incident occurred related to SMS-Based 2FA reporting to [30]was through SIM Swap, an Instagram username was hijacked. The damage could have beenworse if the bank account was synchronized with the cellphone. Mobile phone trojans, wirelessinterception, SIM swap attack, are some of the attacks on SMS.

2.2.7.2 Quick Response Code (QRCode)

QR codes, are two-dimensional matrix barcodes that are used to encode information, likenumbers, letters and Kanji characters, most common use case is to encode a link or other textualinformation to make it instantly available [12, 32]. It was invented in 1994 by Denso, one ofmajor Toyota group companies and used for automotive industry [65], but nowadays have gainedpopularity as part of the Internet of Things (IoT), and since smartphones were equipped with acamera and scanning software. A QR code is displayed on the screen and is then conveyed tothe mobile phone through the mobile phone camera, making the log in process is quicker andeasier than typing a username and password. The user does not need to memorize the secretand this method is also immune to keyloggers.

QR codes compared to barcode, stores more information in a smaller space, which makes itmore efficient. Sizes, error correction levels and how much information can be stored in the QRcode is standardized in ISO/IEC 18004.

QR codes verification mechanism should be used instead SMS based OTP, is a practical, ef-

Page 41: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

2.3. Comparative 19

fective an reliable alternative in application or web service that required two-factor authentication.Studies[32] show why the user is still susceptible to QR Code based attack and recommendationson how smartphone applications can effectively protect users against malicious QR codes.

2.3 Comparative

We use the rating criteria with the exception of the phishing protection of [6] to which we addthe qualifications defined in [35] for the security key to compare the authentication methodsdefined above, cryptographic smart card (which we call only smart card), Google Authenticatorthat is the authenticator type used now for Keycloak for OTP, and FIDO2. The comparisonscan be seen in table 2.1.

Table 2.1: Comparative evaluation of the various similar authentication methods schemes.Adapated from [6, 35]

Usability Deployability Security

Category Scheme Mem

oryw

ise-E

ffortless

Scalab

le-fo

r-Users

Nothing

-to-Carry

Physically-E

ffortless

Easy-to-Le

arn

Eficient-to-U

se

Infreque

nt-E

rrors

Easy-R

ecovery-from

-Loss

Accessib

le

Neglig

ible-C

ost-pe

r-User

Server-C

ompa

tible

Browser-Com

patib

le

Mature

Non

-Proprietary

Resilient-to-P

hysic

al-O

bservatio

n

Resilient-to-Targeted-Im

person

ation

Resilient-to-T

hrottle

d-Gue

ssing

Resilient-to-U

nthrottle

d-Gue

ssing

Resilient-to-Interna

l-Observatio

n

Resilient-to-Leaks-fr

om-O

ther-V

erifiers

Resilient-to-P

hishing

Resilient-to-T

heft

No-Tr

usted-Third-Party

Requirin

g-Ex

plicit-

Con

sent

Unlinka

ble

(incumbent) Web passwords • • • ◦ • • • • • • • ◦ • • • •

Password ManagerFirefox ◦ • ◦ ◦ • • • • • • • • ◦ ◦ • • • • •LastPass ◦ • ◦ ◦ • • • ◦ • ◦ • • ◦ ◦ ◦ ◦ ◦ • • • •

Hardware Tokens

Security Key ◦ ◦ • • • • ◦ ◦ • • • • • • • • • • • • •RSA SecurID • ◦ ◦ • • • • • • • • • • •Yubikeys • ◦ ◦ • • • • • • • • • • • •SmartCard (Crypto) ◦ ◦ ◦ ◦ ◦ • ◦ • • • • • • • • • • • •FIDO2 • • • • • • • ◦ ◦ • • • • • • • • • • • •

Phone BasedOTP over SMS • • ◦ • ◦ ◦ ◦ • • • • • • • • • ◦ • •Google Authenticator ◦ ◦ • ◦ • • • ◦ ◦ • • • • • •

◦ = almost offers the benefit; • = offers the benefit; no circle = does not offer the benefit.

Usability

Smart card: Crypto smart card, which is the case of Citizen Portuguese Card and the smartcard used with IsoApplet, offers quasi-memorywise-effortless and quasi-scalable-for-users-benefits,because the user must still enter the authentication PIN. In the case of the Citizen PortugueseCard also quasi-nothing-to-carry because users do not need to carry an additional physicalobject. It is not physically-effortless because users must enter the authentication PIN. It isquasi-easy-tolearn because to start using, is necessary to install the middleware of the PortugueseCitizen Card and also add the module in the browser, and is infrequent-error because the useronly needs to enter the 4-digit PIN. However, it is not easy-to-recovery-from-loss.

FIDO2: It offers the benefits of memorywise-effortless is not necessary to enter the password

Page 42: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

20 Chapter 2. State of the Art

as is the case, for example of U2F security key, scalable for the user because a single device can beused in several accounts, does not offer the benefit of nothing-to-carry that it is necessary to carrywith an additional FIDO2 device to be able to authenticate. However, it is easy-to-learn, efficientto use and physically-effortless, easy-to-learn, efficient-to-use, and infrequent-error because it isnot necessary to user type nothing.

Google Authenticator: It is not memorywise-effortless, scalable-for-users, physically-effortlessand infrequent-error, because the user must enter before, as the first factor, username andpassword, while offering the benefit of quasi-nothing-to-carry, because only the phone is necessary,it is efficient-to-use and quasi-easy-to-learn because is necessary to install the application andconfigure it.

Deployability.

Smart card: It is Negligible-Cost-per-User, user can use the same smartcard with IsoAppletor the Portuguese Citizen Card in different web sites. It is not Server-Compatible, but it isalmost quasi-browser-compatible it is necessary to add the module in the browser and installthe middleware to be able to communicate with the smartcard, it is not accessible because asuccessful authentication requires to enter the authentication PIN.

FIDO2: offers a quasi-negligible-cost-per-user, because the user only need one token and canuse it for several accounts. It is not server-compatible, but it is quasi browser-compatible, multipleimportant web browsers, including Chrome, Firefox and Microsoft Edge, have implemented thestandard[2].

Google Authenticator: it is compatible with the browser, is browser-compatible, matute andnegligible-cost-per-user, only need a phone where can have and associate all the OTP relatedto the account. It is not accessible because it is necessary to read the generated code and theninsert in the log in page.

Security.

Smart card: the crypto smart card scheme is Resilient-to-Phishing through digital certificates,in addition the server must trust the CA who signed the certificate installed on the smart card.It is Resilient-to-Targeted-Impersonation, Resilient-to-Throttled-Guessing, It offers Requiring-Explicit-Consent as you insert the PIN, It’s Resilient-to-Theft thanks to the use of a PIN.

FIDO2: it is resilient-to-phishing, because is an extension of FIDO U2F, and offers the samelevel of high-security based on public key cryptography, this means, that generate assertions thatprotect users against phishing and website attackers[79]. The security ratings can be consulted in[35], It’s Requiring-Explicit-Consent because the proof of position is required (touch the device).It is non resilient-to-theft because it is not requires a password as first factor.

Google Authenticator: Because its use requires both a regular password and a one-time secretfrom the phone, the scheme is generally resistant to guessing and observation attacks; however werate it only quasi-resilient-to-physical-observation and quasi-resilient-to-targeted-impersonation

Page 43: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

2.4. Authorization 21

because the OTP is valid per 60 second means the one-time password can be used in this 60second to impersonation. It is Resilient-to-theft because it requires a password in addition topossession of the phone, the scheme is currently no-trusted-third-party as Google is the onlyverifier, it is requiring-explicit-consent (OTP must be typed again).

2.4 Authorization

These are related to the restrictions on the actions of the authenticated users, respond to thequestion, "are you allowed to do this?".Usually, they work in the following way: the permissionsare associated with roles, and roles are assigned to each user, which in turn, makes possible toknow what a user is allowed to do.

2.5 Single Sign-On

Single Sign-On (SSO) is a mechanism that uses a single action of authentication to permit anauthorized user to access all related, but independent software systems or applications withoutbeing prompted to log in again at each of them during a particular session[55]. This providesa great user-friendly environment since logging in only once allows the user to access severalapplications or systems. Which means that SSO systems support automatic user authenticationto Service Providers (SPs), but for this purpose and as authentication implies identification,SSO systems need to handle user identifiers, called SSO Identifiers. An example of this typeof mechanisms is Google, with the Google account it is possible to access its different services,such as Maps, Drive, Photos. Without an SSO system, users enroll with many SPs, sharesauthentication secrets, e.g., password, and need to remember as many username and passwordsas SPs, as shown in figure 2.6.

When a user has to manage different password for several accounts andand has to rememberall the passwords it becomes a stressful task known as password fatigue, what leads the userto choose easy passwords or reuse them in different applications, so the impact of a brute forceattack would be enormous. An example of this problem is the the cyber attack that Adobesuffered in 2013 [5], where thousands of user data were compromised, including passwords.

Among the main disadvantages of the SSO mechanism, there is a simple point of failure.That is, if the identity provider fails, the user can not be authenticated. If an attacker achievesto authenticated will have access to several associated services. In this type of systems, it iscrucial to have a strong authentication method.

Based on the architecture of an SSO system[10, 55], they can be classified as follows:

• Simple SSO, it is easy to implement, it involves a single authentication authority anda single set of credentials for each user, but this does not imply that there is a single

Page 44: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

22 Chapter 2. State of the Art

SP 1 SP 2 SP n

Figure 2.6: Access to multiple SP with different credentials

authentication authority, but that single authentication authority may consists of multipleauthentication servers.

• Complex SSO, involves multiple authentication authorities and multiple sets of credentialsper user and many authentication protocols. Which for single set of Credentials can be:

- Token-Based, when a user authenticates successfully, receives a temporary token, thistoken can be cached and reused to prove the user’s identity to other TTPs.

- PKI-Based, uses a PKI certificate that is validated against a trusted CA for allfederated SSOs.

And for a multiple set of credentials, according to [55], the credentials are cached, on theclient side, or on the server, and are independent for each authentication authority. Or thecredentials can be synchronized between credential databases of different authenticationauthorities, but this technique is not considered a true SSO, and its use is not recommended.

2.5.1 SAML

Security Assertion Markup Language (SAML) is the oldest standard of the next two, it is aprotocol for authenticating web applications, it provides authentication and authorization.

The SAML protocol exchanges authentication and authorization data in XML format, solutionto perform SSO which allows users to gain access to website resources in multiple domainswithout reauthentications. It was developed by the Security Services Technical Committee of thestandards organization, the Organization for the Organization for the Advancement of StructuredInformation Standards (OASIS) for exchanging user security information between enterprisesand service providers.[77]. SAML defines the way to exchange authentication and authorizationdata but does not specify how to authenticate the user, the authentication aspect is not definedin the protocol, so developer is free to choose.

The three roles involved in this data exchange are:

• Identity Provider: Asserting party, who produces assertions about a subject(user and theiridentity).

Page 45: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

2.5. Single Sign-On 23

• Service Provider: the web application where user is trying to gain access. Who receivesthe assertions and issues an authorization decision statement based on the assertions of theidentity provider

• The User: called "principal" terminology used in SAML to refer to the End-User trying toaccess the resource.

The authentication process between these roles is shown in the figure 2.7.

In SAML there is an Assertion, an XML document digitally signed that contains assertinginformation about the user. The relying party assumes that all data contained in the assertionfrom the asserting party is valid[40]. The equivalent in OpenID Connect is the ID token. Thisassertion needs integrity protection, for this purpose is transported over a secure connection, forexample over SSL/TLS and/or it be digitally signed.

Three kinds of statements that can be carried within an assertion are defined by SAML [26]:

• Authentication statements these are issued by the party that successfully authenticated theuser, describe a subject authentication event.

• Attribute statements provide specific details of the subject.

• Authorization statements define something the subject is entitled to do, indicate whetherthe subject has permission to access a particular resource (e.g. Alice is permitted to modifyusers username).

User Agent (Browser) Service Provider(SP)

(relying party) Identity Provider(IdP)

(asserting party) 1. User agent attempts to access resource

at the service provider

2. Redirect to request SAML authentication assertion 3. Forward SAML authentication request

4. Challenge for authentication

5. Successful challenge response

6. Return SAML authentication assertion 7. Present SAML authentiication assertion

8. User logged

Figure 2.7: SAML authentication flow

2.5.2 OAuth2

OAuth 2.0 is not an authentication protocol, is a delegation protocol, a means of letting someonewho controls a resource allow a software application to access that resource on their behalf

Page 46: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

24 Chapter 2. State of the Art

without impersonating them, enables a third-party application to obtain limited access to anHTTP service[25, 61], in others words, it allows a web service to act on our behalf. Also, it offersan alternative so that third party services do not need to have our username and password stored,thus avoiding that in the case that the third party is compromised, the data of the end-userprotected by that password is still safe.

OAuth introduces an authorization layer to separate the function of the client from thatof the resource owner. The client requests authorization from the owner of the resource andreceives security credentials, called access token, which can be used to access the resource. Thistype token of is issued to third-party clients by an authorization server with the approval ofthe resource owner. OAuth is not defined outside of the HTTP protocol. Since OAuth 2.0 withbearer tokens provides no message signatures, it is not meant to be used outside of Hyper TextTransfer Protocol Secure (HTTPS) (HTTP over TLS)[61].

The authorization server packages whatever information of protected resource into a JSONWeb Token(JWT), defined in [43] as a compact, URL-safe means of representing claims to betransferred between two parties. Unlike SAML, the token is a JWT and OAuth does not definea token format, the token content is completely opaque to the client application, what the clientdoes is forward the received token from the authorization server to the protected resource. It isthe protected resource, which needs to understand the token, analyze the information and makeauthorization decisions based on the information received. As the protected resource relies onthe information contained in the token, it must be protected, so that when it passes through theclient it is not manipulated. There is the JSON Object Signing and Encryption standards(JOSE)that does this. These tokens is sent in Base64URL-encoded JSON format, and are valid onlyfor a period of time that is defined within the token, along with other information, called JWTclaims, as shown in the figure 2.8.

c) access_token value from (b) in Base64URL

a) Simple set of user data b) OAuth access_token

Figure 2.8: Example of OAuth access tokem [61]

According to [25] there are four roles defined in OAuth:

• Resource Owner: Entity that has the information to which the client wants to access, thatis, who is able to grant access to the protected resource (usually an end user).

• Resource Server: The server hosting the the resource owner’s protected resources, able toread access tokens and respond to requests for protected resources.

Page 47: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

2.5. Single Sign-On 25

• Authorization Server(AS): Which issue access tokens (security credentials) to the clientafter successfully authenticating the resource owner

• Client: an application requesting access to the protected resources on behalf of the resourceowner.

Thus, the resource owner (e.g. Alice) is delegating the responsibility to authorize access toher resources (e.g. Alice’s photos) hosted on the resource server (photos.google server), to theauthorization server (e.g. accounts.google.com server).

In the figure 2.9 can be seen the OAuth process

ClientResource Owner Authorization Server(AS) Protected Resource

Client requests authorization

Resource owner grants authorization

Client sends authorization grant

Authorization server send access token

Client sends access token

Protected resource sends resource

Figure 2.9: OAuth process flow. Adapted from [61]

2.5.3 OpenID Connect (OIDC)

OpenID is an SSO protocol, solves the problem of the OAuth2 protocol, and already considersauthentication and authorization, which is achieved by combining OpenID authentication andauthorization through the OAuth2 protocol. That is, OpenID Connect creates an identity layerover OAuth 2.0, the identity layer is abstracted in an ID token, and an OAuth authorizationserver that supports OpenID Connect returns an ID token in addition to the the access token. Aprotocol which allows any web server to act as an identity provider [57].

OpenID is a decentralized system, no central authority should register the relying party(RP)or the OpenID providers(OP), each End-User is free to choose which provider of OpenID theywant to use. It is based on the concept that using a single URL (instead of submitting a usernameand password, the user submits a URL), applications and resources users can log in to anyOpenID-enabled website. What allows the user to access different sites without having to createa password for each site, only need to register once in an OP. An example is shown in the figure2.10.

Page 48: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

26 Chapter 2. State of the Art

OpenID identifier, also called OpenID, usually contains the OpenID Provider domain nameand the username of End-User, these identifiers take the form of a unique Uniform ResourceIdentifier(URI), for example: username.example.com or http://example.com/username.

According to OpenID website [16] it already has more than 50,000 sites that accept OpenIDlogin and is gaining more and more acceptance. Several organizations such as Google, Facebook,linkedIn, Yahoo, among others, issue and accept OpenID.

Email

Password

Remember me

Log In

Login with Facebook Login with LinkedIn

Figure 2.10: Login using OpenID Connect Protocol

The difference between OpenID Connect and OAuth2 is the ID token, which has some securityfeatures such as a nonce and an access token hash. In OAuth2 there is no ID Token.

An ID Token is a JSON Web Token(JWT) that contains claims about the authenticationevent. It may contain other claims, for which the OpenID Connect specification defines a set ofstandard claims [62].

The ID Token contains information about the user identity, resembles an identity card,and is signed by the OpenID provider (identity provider). It can optionally be encrypted forconfidentiality. An example of a ID Token generated by Keycloak can be seen in the figure 2.11.

Figure 2.11: ID Token packaged in a JSON object:

Below the definition of each user claim, according to [62].

Page 49: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

2.5. Single Sign-On 27

• sub: (Subject) The local identifier of the authenticated user

• iss: (issuer) Identifies the entity that issued the Token.

• aud: (audience): It is generated for a particular audience for example client, it can be amatrix of identifiers.

• nonce: new parameter (optional) that the client application can include to mitigate replayattacks. The authorization server must reject any request if it finds another request withthe same nonce value.

• auth_time: Contains the time when the end user is authenticated by the authorizationserver. In the case that the user is already authenticated, he can not authenticate again.

• acr: Authentication context reference, value that must be understood by both theauthorization server and the client application.

• iat: (issued at) The time the token was issued, in milliseconds.

• exp: (expiry) The timestamp after which the token expires in milliseconds.

2.5.3.1 Roles

Within the OpenID Connect protocol three different parties implying three different roles can befound[62].

• The End-User, which is Human participant, represented by a User Agent (UA), who wantsto access a service provided by the client, but to get access needs to prove its identity tothe Client.

• The Client, (Relying Party in OpenID terminology), an application or website that providesa service where the End-User authentication is mandatory.

• The OpenID Provider(OP), which is the Identity Provider(IdP), the Trusted ThirdParty(TTP), that handles the authentication of the End-User and the one in chargeof issuing the token ID token and access token (if is required).

The OpenID abstract protocol is shown in the figure 2.12

2.5.3.2 Protocol Flow

• Authorization code flow a browser-based protocol, returns an Authorization Code to theClient, which can then exchange it for an ID Token and an Access Token directly. Whenusing the Authorization Code Flow, all tokens are returned from the Token Endpoint[62].It is the most used flow, it offers greater security, since the tokens are not revealed to

Page 50: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

28 Chapter 2. State of the Art

End-User

Relying Party(Client) OpenID Provider

Delegates authentication,requests tokens & claims

Responds with tokens & claims

authenticates, grants access

accesses services

Figure 2.12: OpenID Connect abstract protocol flow

the User-Agent and the client application can also be authenticated. A refresh token isinvolved, which allows the application to obtain a new access token after it expires.

• Implicit flow, all tokens are returned from the Authorization Endpoint, the Token Endpointis not used. The ID Token and if requested, an access token, are returned directly tothe Client [62]. Similar to Authorization Code Flow, it is a browser-based protocol butrefreshes tokens are not involved.

• Hybrid flow, some tokens are returned from the Authorization Endpoint and others arereturned from the Token Endpoint[62]. A combination to authorization code and implicitflow, rarely used.

2.6 Authentication Servers

In this section we will describe three types of authentication servers and the reason why wechoose one of them.

2.6.1 WSO2 Identity Server

WSO2 Identity Server, written in JAVA, released in 2008, is an open source, provided under theApache 2 license identity and access management server, can be used to simplify the activitiesrelated to identity and access management(IAM) in the company. Single sign-on (SSO) is oneof the key features of the WSO2 Identity Server that provides support for a wide variety ofidentity and access management protocols such as SAML, OpenID Connect, and OAuth, throughwhich it allows users to provide their credentials once and obtain access to multiple applications.Users are not prompted for their credentials when accessing each application until their sessionis terminated[27]. Also provides an API that allows creation of own identity providers that canthen be included to the server. WSO2 runs on its own middleware WSO2 Carbon.

Page 51: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

2.6. Authentication Servers 29

2.6.2 Shibboleth

Shibboleth is an open-source project and provided under the Apache 2 license, that providessingle sign-on capabilities, has been developed by the Internet2 community. A project withintellectual and financial support from IBM [13], meeting the need for collaboration and theexchange of resources within and between organizations, Shibboleth utilizes SAML standards forauthentication and attribute assertions to achieve its purpose [7, 13, 28], is increasingly deployedboth in the U.S. and abroad[4]. The Shibboleth server is one of the most used tools in academicfederations. Shibboleth is one of the most widely used and popular SAML2 identity providers.

In Portugal, it serves as the basis for all federated authentication among all the PortugueseUniversity networks, since a national federation of authentication and authorization infrastructurescalled RCTsaai was created by Fundação para a Ciência e Tecnologia(FCCN), with the aim ofproviding access to web services made available by the universities associated with the RedeCiência, Tecnologia e Sociedade(RCTS).

The University of Porto recently made available its authentication and authorization infra-structure called UPORTOaai to integrate the RCTSaai National Federation, the UPORTOaaian Shibboleth server, in addition to password authentication, making other options availablesuch as authentication by Cartão do Cidadão Português(CC) and Chave Móvel Digital(CMD),the latter is a means of authentication that allows the association of a mobile phone numberwith the Civil Identification Number(NIC) for a Portuguese citizen and the passport number fora foreign citizen[3]. .This way they take advantage of the SSO to simplify the task of managingthe password in several systems, since they access resources through the credentials provided andmanaged by the origin institution(identity provider) and passes the minimal identity informationnecessary to the service provider.

2.6.3 Keycloak

Keycloak is an authentication server released in 2014, written in JAVA, open-source and providedunder the Apache 2 license, services and access control for web applications[59]. This means thatapplications do not have to deal with login, authorization, or user registration pages. In this way,users authenticate the Keycloak server and do not need to authenticate to different applications,using SSO technology, is based on standard protocols and provides support for OpenID Connect,OAuth 2.0, and SAML, the SSO solution support multiple realms (domains).

Also, provides a Service Provider Interface(SPI) that allows create and add custom providerauthenticator and thus extending functionality. Keycloak has a powerful user interface whichprovides, administration of clients, users, authentication management, among others. Fromversion 4, Keycloak allows to add new pages to the User Account Management Console, withouthaving to modify the classes already defined, they have already implemented a new provider(ThemeResourceProvider) that can be used to load additional templates and resources. In figure3.7 an overview of the Keycloak classes structure to handle the account pages is shown, it can be

Page 52: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

30 Chapter 2. State of the Art

seen that the pages associated with the user’s account are defined as constants, they can not beextended.

Another positive point of Keycloak is that they have constant updates and a very activecommunity where they help solve problems that arise. Keycloak runs on Wildfly.

2.6.4 Comparisons between the servers

After the comparisons between the servers, see the comparative table 2.13, we chose Keycloakbecause, in addition to the SAML protocol, the protocol used by Shibboleth also allows OpenIDConnect and OAuth. OpenIDConnect is a newer and easier to configure technology than SAML,being the main reason why we discarded Shibboleth. Now we will focus only on WSO2 andKeycloak.

Whereas WSO2 and Keycloak have similar characteristics, according to [49] WSO2 wascertified by OpenID in January 2018, while Keycloak in November 2016 and in an investigationresult[8] they said that In theory, WSO2 IS supports external identity providers, but in practicewe encountered difficulties configuring the Public Key Infrastructure (PKI) trust store so that itwould accept the Certificate Authority(CA) of CILogon’s SSL certificate..

Another important difference between WSO2 and Keycloak is the middleware, WSO2 usesits own WSO2 middleware which means that the amount of information available on the webwill be lower, compared to all the existing experience and information in the case of Wildfly,middleware that uses Keycloak.

• In Keycloak a super user can handle all the realms, while WSO2 does not have thisfunctionality.

• Keycloak installation is simpler, just download and run the standalone, while WSO2 needsadditional middleware configurations.

• Keycloak has a simpler and easier to perceive interface, with one clicks it is possible tocreate a user and to do test, while WSO2 has a more complex user interface

• The Keycloak community is quite active and have several examples that serve as a guideand help to better understand how to create custom authenticator provider, REST resourceprovider, among others.

Page 53: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

2.6. Authentication Servers 31

Figure 2.13: Comparisons between the servers

Page 54: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais
Page 55: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Chapter 3

Design and implementation

In this chapter, we will describe how we implemented the authentication modules for client certi-ficates X509, tokens Universal 2nd Factor (U2F). Besides, the protocol mapper implementationwhich is responsible for sending information about the type of authenticator used by the user atthe time of login to the Relying Party. Furthermore, the necessary configurations to make itwork, also some of the problems we have encountered during work development.

We have implemented these modules extending the functionality of the Keycloak authen-tication server, through Authentication Service Provider Interface (SPI), which is provided byKeycloak and allow creating new out-of-the-box plugins that can then be installed or deploy onthe server. We have also adapted the user account interface to make it easier for the user toregister their certificate or their devices for authentication.

3.1 Authentication SPI

Keycloak provides a series of SPI for which it is possible to implement our customs providers.First, to implement a provider, it is necessary to implement its ProviderFactory and Pro-vider interfaces, in the case of authenticators AuthenticatorFactory and AuthenticatorFactory,it is also necessary to create a service configuration file and add within the JAR META-INF/services/org.keycloak.authentication.AuthenticatorFactory, in order for Keycloak to recog-nize the custom provider. This file must contain a line-separated list of fully classnames of theAuthenticatorProviderFactory implementations, an example of the class structure is illustratedin figure 3.1 so that it can be better understood.

It is also possible to add the custom authenticator through the xml configuration files(standalone, standalone-ha, or domain), but for our authenticator to have the out-of-the-boxfeature, we consider that the best option is to create the service configuration file. This way it isonly necessary to install the custom authenticator provider without any extra configuration.

33

Page 56: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

34 Chapter 3. Design and implementation

<<interface>> Provider

+ close

Extends

<<interface>> Authenticator

+ void authenticate+ void action+ boolean requiresUser + boolean configuredFor + void setRequiredActions

<<interface>> Provider Factory

+ create(KeycloakSession) + init() + getId()

Extends

<<interface>> Authenticator

Factory

Implements

CustomAuthenticator

Implements

CustomAuthenticatorFactory

Figure 3.1: Authenticator SPI class structure illustration

3.1.1 Authentication Flow

As we had previously commented, Keycloak provides an Authentication SPI that allows us towrite plugins that can then be installed on the server. To write these authentication plugins, forthat is important to define the following terms, according to the Keycloak documentation, tobetter understand the authentication flow.

• Authentication Flow: It is a container with all the authentications that must occur, asshown in the figure 3.2 for example Browser-Example, where the Auth Type columnis the name of authentication or action that will be executed.

For each auth type, the Executions Requirement can be configured, which defines howan authenticator behaves in the flow. These Executions Requirement are the following:

– REQUIRED, it should always be executed successfully.

– ALTERNATIVE, the authenticator is optional unless one of them is successful, if onesucceeds the rest is no longer executed unless it is configured as required.

– OPTIONAL, only if the user has configured this type of authenticator is executed,otherwise it is ignored.

– DISABLED, does not execute.

• Authenticator: It is a component that contains the logic to perform authentication, oraction within the flow.

• Executions: It is an object that binds the authenticator to the flow (through the executionsrequirements). Also, the authenticator to the authenticator configuration.

• Executions Requirement: Defines how the authenticator behaves within the authenticationflow, the options are required, alternative, optional, disabled see figure 3.2.

Page 57: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

3.2. Account Management Console 35

Figure 3.2: Authentication flow example

• Required Actions: an action that the user user must perform after authenticating, butonce the action is successful the user must not perform the action again, for examplereestablishing a password or verifying the e-mail.

3.2 Account Management Console

The Account Management Console, shows user information and allows the user to manage theiraccount, such as changing their email or password, view session information, and also configurethe TOTP authenticator to use with Google Authenticator or FreeOTP.

Keycloak in version 3.4, version with which we started working, custom attributes are addedthrough the template account.ftl, that is, by overwriting themes/base/account/account.ftl file,this by the structure of their classes see figure 3.7, which in principle did not allow to extend theclass to add new pages easily, that is, without having to modify the classes already defined. Forthis reason, which we will explain in more detail in section 3.4.3. Besides, in a way will be easilyscalable, we first decided to modify the file "account.ftl".

From version 4 released in early July, Keycloak have already implemented the ThemeResource-Provider with methods that allow to load additional templates and resources, with this newfunctionality is possible to add new pages and JavaScript file to the account theme withoutmodify Keycloak class already defined. To process and send data to the new page within theAccount Management Console, it is also necessary to implement a custom RepresentationalState Transfer (REST) endpoint capable of processing and sending data in JavaScript ObjectNotation (JSON) format see section 3.3.

Page 58: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

36 Chapter 3. Design and implementation

3.3 Custom REST endpoints

In order to extend its core functionality, in addition to the possibility of implementing customsSPI, Keycloak offers the possibility of adding customs REST endpoints, for example, to be ableto trigger functionality on the Keycloak server, which is not available through the default set ofbuilt-in Keycloak REST endpoints.

To add a custom REST endpoint is necessary to implement the RealmResourceProviderFactoryand RealmResourceProvider interfaces, wherein the RealmResurceProviderFactory, through theID attribute is possible to define the resource name (the URI). An the most important methodis getResource() which allows returning an object, which acts as a JAX-RS Resource. A JAX-RS(Java API for RESTful Web Services) that through annotations allow to perform operationsin a REST service, the essential annotations are as follows:

• @POST, this request is used to create a new resource on a server, in others words, a postrequest performs the create operation.

• @GET, this request is used to get a resource from a server, in othres words, a get requestperforms a read operation.

• @PUT, this used to update a resource on a server, in others words a PUT request performsthe update operation.

• @DELETE, this request is used to delete a resource, in others words, the delete requestperforms a delete operation.

• @Path, indicates the relative path to add to the URI to access a class or method, in otherswords, determines the resource you’re requesting for. acceder a una clase o método.

• @Produces, specifies the MIME type that returns a method (json, html, plain, xml, etc.).

• @Consumes, specifies the MIME type that requires a method.

3.4 User authentication through X509 client certificate

The most common use of authentication by X509 certificates is to verify the identity of theserver when using Secure Sockets Layer (SSL), most commonly when using Hyper Text TransferProtocol Secure (HTTPS) from the browser, the browser will verify if the certificate presentedby the server has been issued by a trusted Certification Authority (CA).

For the establishment of a SSL/TLS connection, both parties, (the client and the server)must first trust one another, achieved by performing mutual authentication. The initial stepstarts with the client (in this case the user’s browser) certificate and verifying its authenticity ina CA. If the certificate is valid, the client then proceeds to send its certificate to the server, that

Page 59: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

3.4. User authentication through X509 client certificate 37

also verifies it using a CA. If both steps are successful, the path to the access to the requestedresource is now open, and the mutual authentication is completed (see figure 3.3).

Keycloak supports the login through X.509 client certificates, for this type of authenticationthe server must be configured for SSL/Transport Layer Security (TLS) mutual authentication,protocols that provide data encryption to prevent information disclosure. Authentication byclient certificates is part of the SSL and TLS protocol, the latter is an updated and more secureversion of SSL since it uses stronger encryption algorithms than the SSL protocol and solvesknown vulnerabilities.

Client (browser) Server

Initiate SSL Connection

Return Server Certificate

Return Client Certificate

Prompt user for Certificate

Respond with Certificate

SSL/TLS key exchange

Handshake complete

The client and server exchange encrypted data(challenge), in

order to validate the clientcertificate

Verify Client certificate

Figure 3.3: Interaction to exchange to certificates, the server and client certificates

The necessary configurations to enable mutual authentication are the following:

In order to perform authentication based on X.509 certificates, the first thing to do is toenable the SSL/TLS connection in Wildfly by specifying the SSL/TLS context that you want toprotect.

This is achieved by configuring the security-realm(the most important configuration), sinceit is the one that defines the SSL secure context, then enabling the HTTPS Listener that is incharge of providing secure access to the server, here the security-realm is referenced. In the nextsection, it is explained in more detail.

3.4.1 Keycloak configuration for mutual authentication

Is necessary to modify the configuration file standalone.xml located in:

$KEYCLOAK_HOME/standalone/configuration/standalone.xml

<security-realm> element configuration:The attribute used mainly for configuration security of server management interfaces and remoting.

Page 60: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

38 Chapter 3. Design and implementation

The security-realm that must be defined within the <security-realm> element.

It consists of the element <server-identity> where are defined as the server is presentedto the outside world and allows to configure a password for when a remote output connectionis established, as well as providing an <ssl> element which allows to define how to load keysX.509 for incoming and outgoing SSL connections.

The <keystore>element is where the path to the keystore file is set, and the place wherethe certification chain and the private key used to establish the SSL connection. The passwordthat protects the file is specified in <keystore-password>. The format of the keystore filecan be Java Key Store (JKS) or PKCS12, format specified in the class KeystoreUtil.java(see figure 3.4).

Figure 3.4: Keycloak keystore format definition in KeystoreUtil Class

The <authentication> element is used to configure the authentication of an incomingconnection, and by default the authentication mode is <local> i.e. user and password. In thecase of mutual authentication, it is necessary to add to the authentication the <truststore>element, which allows pointing to the storage file of trusted clients certificates within the SSLcontext. In this way, if you have the trusted CA within the <truststore>, any certificateof the client that is signed by this CA or is part to the certification chain of the CA, will alsobe trusted, making unnecessary to add each one independently. It is also necessary to specifythe password that protects the keystore file in the element <keystore-password> (see anexample of the configuration in 3.1).

� �<security-realm name="ssl-realm">

<server-identities>

<ssl>

<keystore path="localhost.p12"

relative-to="jboss.server.config.dir"

keystore-password="secret"/>

</ssl>

</server-identities>

<authentication>

<truststore path="rootCA.p12" relative-to="jboss.server.config.dir"

keystore-password="secret"/>

</authentication>

</security-realm>� �Listing 3.1: Example of the standalone.xml file configuration

It is necessary to configure the listeners in <https-listener> element, to provide secureaccess to the server.

Page 61: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

3.4. User authentication through X509 client certificate 39

� �<https-listener name="https" socket-binding="https"

security-realm="ssl-realm" verify-client="REQUESTED"

enable-http2="true"/>� �Listing 3.2: Example of https-listener configuration in standalone.xml

The https-listener is configured in the subsystem Undertow.This subsystem is the defaultweb server in the Wildfly application server [60]. The attributes that need to be configured are:

• name: the chosen name for the web server.

• socket-binding: the logical name that was defined for a socket and which is associated to aport, in this case, https, to define this relation socket-port name, the <socket-binding>element is used.

• security-realm: that will be used for the SSL/TLS configuration, which has been previouslydefined. In security-realm element, the keystore a truststore are defined.

• verify-client: REQUESTED or REQUIRED are values that must be used in the case ofmutual authentication where the server requests or requires the client to send its certificate.

In this project, we used the XCA graphical tool to create the server and client certificates,but they can also be generated with the Keytool or OpenSSL tools. The self-signed certificate isvulnerable to man-in-the-middle attack since a trusted CA does not verify it, but it was chosenbecause they were only used for tests.

Configuración Certification Authority(CA) Certificates are generated and issued by atrustworthy authority named certification authority (CA). The security policy of a CA describesthe lifecycle of key pairs and their attributes, and sets the validity period of a certificate [76].

For a certificate to be considered valid it must be signed by a trusted CA. We started bygenerating a pair of RSA keys of size 2048, and we configure a CA that will be responsible forsigning the certificate generated for the server and the client(s) (see figure 3.5). This certificateis what is known as self-signed, to obtain a certificate that recognizes your browser, you mustissue a Certificate Signing Request (CSR) to a CA. Then the CA will return a signed certificatethat can be installed on the server. But most of these services are not free.

In the element truststore of the configuration file standalone.xml, we need to set thecertificate of the rootCA, so the server is able to verify if all the certificates were signed by thatCA and their trustworthiness.

Care must be taken in generating the certificate for the server, the common name (CN)must match the name of the host (the domain to which we are going to connect), in this case,localhost.

Page 62: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

40 Chapter 3. Design and implementation

Figure 3.5: RootCA certificate configuration

Figure 3.6: Server certificate configuration as localhost

The certificate already signed by the CA is exported in a .p12 file (standard PKCS12) andthen referenced as keystore in the standalone.xml configuration file. PKCS#12 defines the fileformat that is commonly used for transferring personal identity information and its used to storethe private keys[54].

The certificates issued to the client are created following the same steps to create the servercertificate.

Keycloak has a client authentication module through X.509 certificates, in which the followingidentity sources are supported[22] :

Page 63: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

3.4. User authentication through X509 client certificate 41

• Match SubjectDN using regular expression

• X500 Subject’s e-mail attribute

• X500 Subject’s Common Name attribute

• Match IssuerDN using regular expression

• X500 Issuer’s e-mail attribute

• X500 Issuer’s Common Name attribute

• Certificate Serial Number

We decided to add a new identity source type "SubjectDN and Serial Number", which can beextracted and associated to a user in the user’s account interface. This step provides anotherlayer of security, and in turn, gives the user more flexibility when associating a certificate withhis account. For this purpose we created a new SPI, and the user account interface was modifiedto allow the user to associate a certificate with their account.

3.4.2 Development of the X.509 Certificate Authentication SPI

In Figure 3.7 it is possible to have an overview of the structure and organization of classes relatedto account form. We started working with version 3.3 of Keycloak.

<<enumetarion>> AccountPages

AccountPasswordTOTPFederated_IdentityLogSessinosApplicationsResourcesResource_detail

Templates

+ getTemplate(AccountPages):String

FreeMarkerAccountProvider

(implements AccountProvider)

<<interface>> AccountProvider

 setUriInfo(UriInfouriInfo): AccountProvider setHttpHeaders(HttpHeadershttpHeaders): AccountProvider createResponse(AccountPagespage): Response setUser(UserModeluser): AccountProvidersetProfileFormData(MultivaluedMap<String, String> formData): AccountProvidersetRealm(RealmModel realm): AccountProvider                                                .                                                .                                                . setAttribute(String key, String value): AccountProvider

Implements

it's used in

Figure 3.7: Keycloak class overview

In order to process templates, keycloak makes use of the java Apache FreeMarker library,which is a template engine, to generate output (HTML web pages, e-mails, configuration files,

Page 64: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

42 Chapter 3. Design and implementation

source code, etc.) based on templates and changing data. Templates are written in FreeMarkerTemplate Language(FTL) [17].

In this stage and as you can see in figure 3.7, in the AccountPage class are defined all thepages that can be accessed from the user’s account console. Keycloak does not allow the user’saccount to have exclusive pages to manage the certificates or another authenticator method,only has exclusive pages for administrator passwords or TOTP. On the other hand, Keycloakallows extending the functionality through attributes associated with the user, information thatis recorded in the table user_attribute, therefore we will focus on extending the functionalitytaking advantage of the "attributes" field.

However, starting from Keycloak version 4, it is already possible to create new templates andadd it to the user account management interface as new pages, without the need to modify theexisting Keycloak classes, in section 3.4.3 we will explain in more details.

First we need to configure the jboss-deployment-structure.xml file, which allows set updependencies on other components and load third-party jars and modules, in this case we needdependencies of The Bouncy Castle Crypto API to work with X.509 certificates.

We started by adding two new attributes, one "subjectDN_SN" that stores the concatenationof the SubjectDN information and the Serial Number. Both obtained respectively from the clientcertificate in PEM format. In order to fit all this information, the size of the attribute table hadto be increased, since the default 255 bytes were not enough.

The identity of the user extracted from the certificate can be mapped through the username,email or attribute, we choose the latter to extend the page of Account Management Console. Usingthe attribute avoids the need that the certificate must necessarily contain the user’s informationsuch as the username or e-mail. Then, we can obtain an unique identifier of the certificate, theSubject DN plus the Serial Number, and record this information within the attribute (we willexplain in more detail in the next section with more details on the implementation). In this way,it will be easier for the user to manage their certificates, as long as the certificate is signed by atrusted certificate authority that is registered in the truestore of the keycloak server (configuredin the standalone.xml file). An overview of the classes implemented in the keycloak server canbe seen in the figure 3.8 .

A new authenticator must implements the Authenticator interface, and we must also havea class that implements the Authenticator Factory interface, thas is responsible for creatinginstances of an authenticator and provides metadata of its deployment and configuration, seen inmore detail see 3.1. In the Authenticator Factory we configure the Executions Requirementthat we want to be available see code 3.3. Another important method of worth being mentionedis the isConfigurable() which, is a flag that specifies, within the administrator console, thatthe authenticator can be configured and whose configurations are a list of objects of the typeProviderConfigProperty that the method getConfigProperties() is responsible toreturn.

Page 65: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

3.4. User authentication through X509 client certificate 43

UserIdentityExtractor

getSubjectDnSN()

AbstractX509ClientCertificateAuthenticator

getSubjectDnSn()UserIdentityToModelMapperX509AuthenticatorConfigModel

AbstractX509ClientCertificateAuthenticatorFactory

getConfigPorperties()set List<ProviderConfigProperty> configPropiertiesisConfigurable()

UserIdentityToModelMapper

UsernameOrEmailMapper UserIdentityToCustomAttributeMapper

X509ClientCertificateAuthenticator

authenticate()

extends

X509AuthenticatorConfigModel

enum IdentityMapperTypeenum MappingSourceType

X509ClientCertificateAuthenticatorFactory

getRequirementChoices() getId()X509ClientCertificateAuthenticator()

extends

<<interface>>AuthenticatorFactory Implements

Instance the X509ClientCertificateAuthentication

<<interface>>Authenticator

Extends

Figure 3.8: X509 Client Certificate Authenticator classes overview

• X509ClientCertificateAuthenticator: To create an Authenticator, the class must implementthe Authenticator interface, in the Authenticator interface and the most important methoddefined is authenticate, which is the initial method that the flow invokes, is responsiblefor obtaining and validate the certificate, extract the credentials of the user accordingto the configurations of the authenticator (e.g Subject’s CommonName, SubjectDN andSerialNumber, etc.). The chain of certificates is obtained from the HttpRequest and isstored in an array of X509Certificates where the certificate in the zero position is thecertificate of the current client. The method to get the client certificate is defined like:X509Certificate[] getCertificateChain(HttpRequest httpRequest).

• UserIdentityExtractor: This class is responsible for processing the certificate and obtainingthe identity of the user, and is were we add the new method responsible for returning thecertificate SubjectDN concatenated with the Serial Number.

• UserIdentityToModelMapper: Defines the find() methods, in charge of looking forthe user that matches the attribute, username or email depending on the configurationestablished in the authenticator.

• X509AuthenticatorConfigModel, It is the class that defines the enums IdentityMapperType(User_Attribute and UserName_email) and MappingSourceType, where we add SUB-JECTDN_SN. These enums are referenced in the Authenticator Factory. An enum type isa special data type that enables for a variable to be a set of predefined constants[50].

• X509ClientCertificateAuthenticatorFactory: In this class the configurations of the authentic-ator are defined, that is, the configurations that can be made through the administrator con-sole. This class extends the abstract class AbstractX509ClientCertificateAuthenticatorFactory

Page 66: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

44 Chapter 3. Design and implementation

class in which the entire implementation related to this authenticator is separated. Theauthenticator Factory is responsible for creating instances of an authenticator, in thiscase the X509ClientCertificateAuthenticator, provides metadata for deployment andconfiguration of an authenticator. They have the methods getId() which is the uniqueidentifier of the component, and create() to allocate and process the authenticator. Inthis class we configure the requirement Executions that we want to be available, through thegetRequirementExecutions method, seen in the example code 3.3. Another importantmethod worth of mentioning is the isConfigurable() which is a flag that specifies insidethe administrator’s console that the authenticator can be configured, the configurationsthat we want to be available must be specified within the getConfigPropierties()method, which returns a list of configuration properties of type ProviderConfigProperty

• X509AccountResourceProvider: In this class we implement the REST service for theinformation exchange in JSON format between the server and the template, throughAjax requests from the client, in this case from the exclusive template of the X509Certificate authenticator. To add a custom REST endpoint, it is required to implementthe RealmResourceProviderFactory and RealmResourceProvider interfaces.

We decide to add one more layer of security, and add one that allows you to accept the namesof the wildcard subdomains, i.e *.mydomain.com, which you can also edit in the server XMLconfiguration file. We opted to do it in a friendlier way for the administrator, putting in theadministrator interface as one of the configurations of the authenticator, see figure 3.9

Figure 3.9: Authenticator Configuration

Page 67: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

3.4. User authentication through X509 client certificate 45

3.4.3 User account interface modification

As we said, first we decided to add a new attribute to the page account.ftl, figure 3.10, where theuser can associate the identity of the user contained in the digital certificate. Then we mademodifications to the account.ftl page, adding two new field one where we registered the SubjectDN plus the Serial number and another to show the certificate.In order to work with certificates,we made use of the JavaScript library forge.js, which is a JS Crypto Library that provides aset of tools through which we can process the certificate, and in this way its possible to obtainthe obtain the SubjectDN data and the serial number, enabling us to concatenate it and registerit as a user attribute.

Figure 3.10: Get information from user certificate (first version into account page)

We decided at first to do this because in version 3 of Keycloak it is not possible to extend theaccount page, functionality added only in version 4 of Keycloak launched in June 2018, wherethey implemented the ThemeResourceProvider with the methods needed for this task withoutneeding to modify the structure of Keycloak, as seen in 3.8.

After updating to version 4 of Keycloak, we were able to create a template with Freemarkerand use JavaScript to manage the credentials of each authenticator provider associated with theuser. For this we created a custom REST endpoit, which is a RESTFul web service that arebased on the idea of resource-oriented architecture, and the services are regarded as resources.Each resource is identified by an URI, and can be accessed through AJAX requests to carry outJSON data exchange. Then, we managed to connect our template with the server to access eachresource and perform GET, POST or DELETE operations, where the resource processes thebusiness logic, see figure 3.11. In this way, with the data received from the client, we create anUserCredentialModel object type and associated the x509Credential to the user.

Page 68: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

46 Chapter 3. Design and implementation

CustomREST

endpoint

X509 CertTemplate

requests credentials list (required data from resource)

responds with the credentials list

Figure 3.11: Information exchange between the template and the server.

Below, in the figure 3.12 you can see the final version of the template for handling credentialsof type X509 Certificate provider, which allows to list, register and delete the user credential.

Figure 3.12: X509 Certificate final version template.

To obtain smart card data with IsoApplet and the Portuguese Citizen card, we needed toimplement a service that runs on the client, exclusively responsible for connecting and extractingdata from the certificate stored on the smart card, and then stored as the user’s credential. TheREST API responsible for communicating with the smart card is a service that runs on theclient, in a different domain, and for security reasons, the browser prohibits AJAX calls fromanother origin. For this reason, it is necessary to access through Cross-Origin Resource Sharing(CORS), that allows developers to work with the same idioms as the same domain requests, seenin figure 3.13.

Origin

X509 Template (Client)

Other Domain

GET SubjectDN + Serial Number

Origin: GET SubjectDN + Serial Number

Access-Control-Allow-Origin : "*"Access-Control-Allow-Methods: "GET"

Figure 3.13: X509 Certificate from Portuguese Citizen Card.

When the load button is pressed see figure 3.14, the exchange of information between theclient and the service that is running in the client to get data from smart card begins. The

Page 69: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

3.5. User authentication through U2F Device 47

service first searches for the Applet ID (AID) to check if the card is a Portuguese citizen card orif it is using IsoApplet. The way in which we verify if the applet installed in the smart card isIsoApplet or the applet of the Portuguese citizen card, is through a SELECT APDU commandof the AID, and if the response returns an APDU SW1=0x90 and SW2=0x00, it corresponds toa successful processing (more information about APDUs in section 2.2.3). In case it is IsoApplet,the user must enter the PIN to obtain data of the certificate, which is not necessary in the caseof the Portuguese Citizen Card.

Figure 3.14: X509 Certificate final version template to load certificate data from smart card.

3.5 User authentication through U2F Device

As we said in the section 2.2.5.2 we have two flows, one to register the device see figure 3.15 andanother for authentication see figure 3.16. Before the user can authenticate with the device, it isnecessary to enrroll the device with the service.

In the registration flow, accoding to [35] the server, the realying party generates a randomchallenge, links it and sends it together with the web origin(AppId), from there it is the clientwho communicates with the device in our case through the JavaScript library and its u2f.register()method. Then The security key generates a new key pair public (Kpub) and private (Kpriv) forthe challenge and web origin, stores the private key (Kpriv) and associates the key pair with therelying party’s web origin. Key Handle h is stored by the server together with public key (kpub).The list of already-registered key handles allows the browser to avoid double registration of thesame Security Key.

The public key (Kpub), along with the Key Handle h, the AppId and the hash of the client data(c) see figure 3.15 are signed with the private key (Kpriv). The security key produces as output aregistration message that includes the public key kpub and the key handle h, as well as the deviceattestation certificate, that the web browser then forwards along with the client data (c) back tothe relying party. The relying party verifies the signature and associates the public key and keyhandle with the user’s account. The AppId for example can be "https://login.example.com" or"https://localhost:8443".

Page 70: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

48 Chapter 3. Design and implementation

AppID, challenge

a

CheckAppID

a; challenge, origin, channel id, etc

c

generate: Kpub, Kpriv,

handle h

Kpub, h, attestation cert, signature(a, c, Kpub, h)

sc, Kpub, h, attestation cer, s

cookieStore: Kpub

handle h

U2FDevice

FIDO Client Browser

RelyingParty

Figure 3.15: U2F Registration Flow

In the authentication flow, accoding to [35] the relying party sent the handle h, AppId andthe challenge to the client, the client usually is the browser. The browser check the AppId,generates the client data and sends the hash of the client data (c) along with the key handleand the AppId to the security key through the method u2f.sign(). The Security key firstretrieves the stored AppId and the private key for the key handle. If the Security Key does notrecognize the key handle, or does not agree that it is associated with the web origin(AppId) thatrequested the signature, it rejects the request. Otherwise, retrieves the private key Kpriv andvalidates that it was generated for that AppId that requested the signature, increases the counterand signs a concatenation of the AppId, client data, and the counter, sends the signed value (s)together with the new value of the counter to the browser (the value of the counter is 32-bit thatincreases with each signature of the segurity key), then the browser sends the relying party andthe server verifies the signature against the public key that has registered and authenticates theuser if the signature matches.

handle, AppID, challenge

a

CheckAppID

h, a; challenge, origin, channel id, etc

c

Looup the key Kprivassociated with h

counter ++

counter, signature(a, c, counter)

scounter, c, s

set cookie

Checksignature

usingKpub

U2FDevice

FIDO Client Browser

RelyingParty

h retrievekey Kpub

fromhandle h

Figure 3.16: U2F Authentication Flow

The easiest way to use U2F in browsers that support U2F is to use the U2F JavaScript APIprovided by Yubico u2f-api.js, enabling web pages to communicate with the U2F token onthe client, consists of two calls one to register the U2F token u2f.register() function thatalso verifies if the device is already registered through an array of signatures, and another to signan identity assertion u2f.sign()

Page 71: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

3.5. User authentication through U2F Device 49

For this new authenticator provider, the most important classes that we define are:

• U2FCredentialProvider, where we define the authenticator ID and the methods to modifyand disable the new credential, keycloak provides a CredentialModel class that allowsregistering, deleting and updating credentials.

• U2FRequiredAction, class responsible for registering the U2F device, through the startRe-gistration and finishRegistration methods provided to the server-side U2F library. To registerthe device, first from the relying party, we start by calling the method u2f.starRegistration(AppId,new LinkedList<>()), method that returns the challenge that will be sent to the client.The client in this case the web page u2f-registration.ftl receives the data returned by thestartRegistration method, we will call it data see code 3.4� �

data: {"appId":"https://localhost:8443",

"registeredKeys":[],

"registerRequests":[{"version":"U2F_V2",

"challenge":"ZPupOtnCyQzU1ztAZipgiRDNB9thpoPAyJmHjO0ujEM",

"appId":"https://localhost:8443"}]

}� �Listing 3.4: Example of the value returned by U2F startRegistration function

and send this data as parameters of the u2f.register() function, function provided bythe U2F JavaScript API to communicate with the U2F Device e.g u2f.register(appId,registerRequests, registeredKeys, callback) the response received from the Security Key(token response), whose returned data are: registrationData, version, challenge, appidand clientData, that are then sent from the client to the relying party which in turn usesthe registrationData and clientData as parameters of the u2f.finishRegistration method,responsible for returning the public key(Kpub) and the key handle(h) see code 3.5, whichwe call registration and associate with the user’s credentials in JSON format.� �

registration: {"keyHandle":"-Pw-3E9fpNWCBH8o1321hO_gcXCFFDqKEEQHsQ-hX3

1jFJ-wPqb2ASbetwA_G0pbtcEQV5Mx_q0Zpsp-UG4Gs1rbGlLCD3QIujXONiib9pM",

"publicKey":"BPez_c15KukZ9SwadjCxJk3_cy64-AgnPF39Y-8GoW7lpbIMn1tPrnPu

BO-Ftvnj6H315OO7cqb23sgYX7KLnBU",

"counter":-1,

"compromised":false}� �Listing 3.5: Example of the value returned by U2F FinishRegistration function

• U2FAuthenticator, class responsible for authenticating the user through the methodu2f.startSignature. This method generates the challenge for each U2F device that theuser has registered, returns the following data: appid, challenge, signRequest (version,challenge, appid, keyHandle) seen in example code 3.6, which are sent by the relyingparty to the client and whose function u2f.sign() provided by the U2F JavaScript APi

Page 72: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

50 Chapter 3. Design and implementation

communicates with the U2F Device, and the response returned by the U2F device arekeyHandle, clientData and signatureData, information that in the relying party throughthe method u2f.finishSignature is verified if it is valid for one of the connected devices.� �

{"appId":"https://localhost:8443",

"challenge":"ZzUPZpuNqwztIPkjQnR5bdplFI6vWmS6sMs0OEYWeFI",

"signRequests":[{"version":"U2F_V2",

"challenge":"ZzUPZpuNqwztIPkjQnR5bdplFI6vWmS6sMs0OEYWeFI",

"appId":"https://localhost:8443",

"keyHandle":"-Pw-3E9fpNWCBH8o1321hO_gcXCFFDqKEEQHsQ-hX31jF

J-wPqb2ASbetwA_G0pbtcEQV5Mx_q0Zpsp-UG4Gs1rbGlLCD3

QIujXONiib9pM"}]

}� �Listing 3.6: Example of u2f.startSignature output, return the challenge for each device that theuser has registered

• U2FAccountResourceProvider, class where the REST service is implemented for theexchange of information in JSON format through AJAX requests from the client, inthis case from the exclusive template of the U2F authenticator.

3.5.1 User account interface modification

The easiest way to use U2F in browsers that support is through the JavaScript API u2f-api.js, which provides a registration function that allows you to register the device see figure3.17. If the device was successfully registered, the FIDO client responds with a tokenResponsewhich is the response from the device, and is used as a parameter in the Keycloak server sideu2f.finishRegistration method. This method returns a DeviceRegistration object that persists onthe server and associated with the user, otherwise an error is raised.

The figure 3.4 shows an example of the value returned by the u2f.startRegistration method.This value is then passed as a parameter to the finishRegistration method together with thetokenResponse returned by the FIDO U2F client. In figure 3.5 you can see an example of theobject returned by the method u2f.finishRegistration, for more details about the implementationsee the section 3.5.

Like the implementation of the user account template for the X.509 certificates in the section3.4.3, the FIDO U2F templates is generated with Freemarker and the access to the resourcesis made through AJAX calls to the REST service endpoint implemented for the FIDO U2Fcredential provider. In figure 3.18 the final version of the template to manage the FIDO U2Fcredential.

Page 73: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

3.6. Custom Protocol Mapper 51

KeycloakServer

FIDO U2FTemplate

sent tokenResponse to register URI

u2f.registrer(appId,                                            registerRequests,                            registeredKeys,                      callback,                      opt_timeoutSeconds)

u2f.finishRegistration(challenge,                            tokenResponse)

saveCredential(realm,                        user,                        credential)

u2f.startRegistration

4

Figure 3.17: Information exchange between the template and the server

Figure 3.18: FIDO U2F template in user account management.

3.6 Custom Protocol Mapper

Applications may want or need to be sent certain metadata in Token ID, Access Token or SAMLAssertion, keycloak allows to define what exactly to send and, has already defined some by defaultlike username and e-mail, seen figure 3.19. A Protocol mappers map things like, username, e-mailaddress to a specific claim in the identity and access token, each mapper has common settings aswell as additional ones depending on which type of mapper. Protocol mapper is configured foreach client, it is possible to configure what claims and assertions are stored in the OIDC tokenor SAML assertion. We needed to sent information about the authenticator type used by theuser when he/she logs in, being this information is important, in the case of restricting access toapplication data and/or resources depending on the type of authenticator used.

In the Clients menu, after opening the Mappers label, pressing the create button, it is possibleto configure others mappers such as hardcode roles, claims and custom attributes. However, aswe need to send the authentication method(s) that were executed at the time of log in, optionthat is not available at the time of this project in Keycloak, for this reason, it is necessary toimplement a custom protocol mapper, in order to set this information in the token claim.

In this section we will explain how we have developed the custom protocol mapper that wecalled Authenticators Protocol Mapper, which implements the class ProtocolMapper, that

Page 74: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

52 Chapter 3. Design and implementation

Figure 3.19: Protocol mapper example for OpenID Connect (OIDC) based client

is in charge of setting the claim token with the type of authenticator configured in theclient session where the user has been authenticated. For this it is necessary to obtain theAuthenticatedClientSessionModel, through which it is possible to access the executions, thatcontain the list of authenticators that were used during authentication.

First of all, we need to add this new type of mapper to the list of options. This is possiblethrough the create method of the ProviderConfigurationBuilder class, responsible forbuilding a list of ProviderConfigProperty instances, that is, through the create method,it is possible to add components like textbox, labels, etc., to the interface, see part of codein 3.7. After defining the list of properties with the method addAttributeConfig, the list ofconfigured properties is set, for the UserPropertyMapper class that has the method setClaimand createClaimMapper.� �

private static final List<ProviderConfigProperty> configProperties;

static {

configProperties = ProviderConfigurationBuilder.create()

.property()

.name(ProtocolMapperUtils.MULTIVALUED)

.label(ProtocolMapperUtils.MULTIVALUED_LABEL)

.helpText(ProtocolMapperUtils.MULTIVALUED_HELP_TEXT)

.type(ProviderConfigProperty.BOOLEAN_TYPE)

.defaultValue(false)

.add()

.build();

OIDCAttributeMapperHelper.addAttributeConfig(configProperties,

UserPropertyMapper.class);

}� �Listing 3.7: Component settings to render into Client Mappers configuration page

Page 75: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

3.7. Authentication Type option into login page 53

Keycloak offers the method SetClaim which is responsible for associating the claim value tothe token. The claim value is represented by an object that in this case is a list type, in the caseof having more than one value, for example for two factor authentication, at this point, throughthe AuthenticatedClientSessionModel class, it is possible to access the executions andthen add the authenticators to the list. The authenticator mapper configuration can be seen infigure 3.20.

It is important to emphasize that, when updating to version 4 of Keycloak, we mustmake small modifications when setting claim data, for that, it is necessary to create a Pro-tocolMapperModel variable and set if the claim value can be multi-value or not, as follows:mapper.getConfig().put(ProtocolMapperUtils.MULTIVALUED, "true")

Figure 3.20: Authenticator Protocol Mapper graphical interface

3.7 Authentication Type option into login page

In this chapter, we explain how the new functionality for Keycloak could be implemented thatallows user to select through a list of options the type of authenticator that user wishes to use tolog in. We will explain the version that we currently have (still in development) and the currentstate of the user interface.

In order to be able to select the authenticator type to be used at log in time. It isnecessary to personalize the authentication flows and create a customized implementationof authenticator SPI. Keycloak provides a set of authenticator requirements, see section 3.1.1.Some executions requirements are ALTERNATIVE and OPTIONAL. ALTERNATIVE definesthat the authenticator is optional until one of them is successful, and if one of them succeeds thenthe rest it does not run. OPTIONAL, is only executed if the user has the respective authenticatortype configured.

Page 76: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

54 Chapter 3. Design and implementation

The Authenticator Selector is a new authentication SPI, and is described how toimplement in the section 3.1.1.

After installing the plugin, the new execution Authenticator Selector is alreadyavailable. Seen in figure 3.21, whose execution requirement is set as OPTIONAL, meaningthat, it will be executed if it is defined.

Figure 3.21: Authentication configuration for Authenticator Selector

After adding the Authenticator Selector, the way it works is as follows:

• It looks for all the authenticators defined as ALTERNATIVE or OPTIONAL following theAuthenticator Selector (the execution flows is in order in which they were added).

• We create a list with all the authenticators types, and then show the list so the user canselect.

In this way, users can already select the authentication method that wants use for log in, seenin figure 3.22. Then the log in page corresponding to the selected authenticator type is displayed.

Figure 3.22: Authenticator Selector page with authentication methods options

REQUIRED executions are always executed, this is why we omitted and not added to the

Page 77: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

3.8. Chapter summary 55

options list, only authenticators which executions requirements are set as ALTERNATIVE orOPTIONAL.

3.8 Chapter summary

In this section, we present a summary of the main problems we had and how we solved it.

In the first development stage, we worked with version 3 of Keycloak (last release at thattime). During this first development stage of the authentication methods, we were quite limited.

We were restricted when we needed to add new pages to the user account management console,in order to enable users to manage their credentials. With this Keycloak version (version 3) itwas necessary to modify the default Keycloak classes in order to recognize new pages. Becauserecognized pages into the user account management are defined as constants, they are Enumtype, seen in figure 3.7.

The creation of the final version of the user account management page was possible after therelease version 4 of Keycloak. This version, provides ThemeResourceProvider class that allowsadding new templates and resources. In our case, we added the FIDO U2F and X509Certificatepages to allow registering credentials of these types at log in time or from the user accountmanagement console.

To be able to interact with the smart card, we had to implement a service that runs onthe client, who is in charge of communicating with the smart card and responsible sending thecertificate data that is required by Keycloak. At this point, we had to decide how to differentiateIsoApplet or the Portuguese Citizen card, and the solution we present is through SELECTAPDU commands asking for which AppletID was installed. We connect to this service throughCross-origin resource sharing (CORS), which allows a user agent to obtain permission to accessresources selected from a server, in a different origin (domain), to which it belongs.

In order to implement the custom authenticator protocol mapper, that is, to send informationto the relying party about the authentication method used by the user for log in, we thank theKeycloak support team that proposed the solution that we used to implement and achieve theobjective.

Lastly, as for the selector authenticator, basically allows the user to select a type ofauthentication method to log in. We solve by modifying the execution status so that onlythe selected type of authenticator is executed. To develop this module, the support of theKeycloak team was also necessary.

Page 78: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

56 Chapter 3. Design and implementation

� �private static final String[] mappingSources = {

MAPPING_SOURCE_CERT_SUBJECTDN,

MAPPING_SOURCE_CERT_SUBJECTDN_EMAIL,

MAPPING_SOURCE_CERT_SUBJECTDN_CN,

MAPPING_SOURCE_CERT_ISSUERDN,

MAPPING_SOURCE_CERT_ISSUERDN_EMAIL,

MAPPING_SOURCE_CERT_ISSUERDN_CN,

MAPPING_SOURCE_CERT_SERIALNUMBER,

//new mapping sourceMAPPING_SOURCE_CERT_SUBJECTDN_SERIALNUMBER

};

private static final String[] userModelMappers = {

USER_ATTRIBUTE_MAPPER,

USERNAME_EMAIL_MAPPER

};

protected static final List<ProviderConfigProperty> configProperties;

static {

List<String> mappingSourceTypes = new LinkedList<>();

for (String s : mappingSources) {

mappingSourceTypes.add(s);

}

ProviderConfigProperty mappingMethodList = new ProviderConfigProperty();

mappingMethodList.setType(ProviderConfigProperty.LIST_TYPE);

mappingMethodList.setName(MAPPING_SOURCE_SELECTION);

mappingMethodList.setLabel("User Identity Source");

mappingMethodList.setHelpText("HelpText..");

mappingMethodList.setDefaultValue(mappingSources[0]);

mappingMethodList.setOptions(mappingSourceTypes);

ProviderConfigProperty certDomain = new ProviderConfigProperty();

certDomain.setType(STRING_TYPE);

certDomain.setName(CERTIFICATE_DOMAIN_NAME);

certDomain.setDefaultValue("");

certDomain.setLabel("Domain Name");

certDomain.setHelpText("Help text");

configProperties = asList(mappingMethodList,

certDomain); // con f i gura t ion for domain name}

public static final AuthenticationExecutionModel.Requirement[]

REQUIREMENT_CHOICES = {

AuthenticationExecutionModel.Requirement.REQUIRED,

AuthenticationExecutionModel.Requirement.ALTERNATIVE,

AuthenticationExecutionModel.Requirement.DISABLED

};

@Override

public AuthenticationExecutionModel.Requirement[] getRequirementChoices() {

return REQUIREMENT_CHOICES;

}

@Override

public boolean isConfigurable() {

return true;

}� �Listing 3.3: Example how add components for the authenticator configuration and the executionsrequirement options (example REQUIRED, ALTERNATIVE, DISABLE)

Page 79: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Chapter 4

Testing and Results

To carry out the tests, we use the OpenID client node-openid-client [64], which is a server-sideOpenID relying party implementation for Node.js. We configured it to authenticate the userthrough modules we developed for Keycloak. This client only authenticates with Keycloak anddisplays the data stored in the received OIDC token.

Through the custom OIDC Token mapper seen in section 3.6, it is possible to map informationof the type of authenticator used by the user and send the client related information that canbe used to demand stronger authentication. At this point, we could not process from Keycloakside the information requesting by the relying party for a specific type of authenticator, but wemanaged to close the session.

For the tests, we use the browser Chrome Version 69.0.3497.100 (64-bit) and Firefox 61.0.2(32-bit), the latter for smart card testing.

4.1 Create a user and set credentials

First, we used the administration console to create a user for testing, in the test realm “demo”together with a temporary password. For this procedure, it is necessary to complete the followingsteps:

• From the menu, click "Users" to open the user list page.

• On the right side of the screen, click “Add User” to see add user, as seen in figure 4.1.

• Complete the form with the user data, and then press “Save”. Only the username isrequired.

• After saving, click the “Credentials” tab to set a temporary password for the new user.

57

Page 80: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

58 Chapter 4. Testing and Results

Figure 4.1: Example user creation

4.2 Configure the authentication flow

A flow is a container for all authentications that must happen during login, registration, andother Keycloak workflows, for more information see the section 3.1.1. Into administration consolecomplete the following step:

• From the menu, click "Authenticator".

• In the “Flows” tab, to add new provider click “Add execution”.

• In the execution flow, you can see the provider list, and you can select it to add to theAuthentication flow. The Auth Type column is the name of authentication or action thatwill be executed.

• By default the “Delete” action is enabled, but if the authenticator is configurable, theaction link also shows the “Config” option.

4.3 Certificate X.509 provisioned in PKCS#12

For the tests of the authentication module through X.509 certificates, we first created thecertificate for the test user using the XCA graphical tool. Then we exported the certificate tothe truststore of the server using keytool [51], following the association of the subjectDN andSerial Number inscribed in the certificate as attributes of the user, obtaining the certificate in thePKCS#12 file format, seen in figure 4.3. This file is commonly used to store private keys withits public key protected by a symmetric key. This way, it is possible to associate the certificateto a user. In figure 4.6, you can see the data of the client’s certificate, after the validation.

Page 81: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

4.3. Certificate X.509 provisioned in PKCS#12 59

Figure 4.2: Authentication flow configuration example

Figure 4.3: Associate X.509 certificate to the user from .p12 file

After associating the certificate with the user, and to be able to send information to therelying party about the authenticator type used by the user to log in, it is necessary to configurethe protocol mapper. The information sent inside the token is the authenticator provider ID. Wemust configure the protocol mapper following the next steps:

• From the menu, click "Clients".

• From the Client list, select the client that we want to configure to receive the authenticatortype information.

• In the Mappers tab, you should see the page similar to the one shown in figure 4.4 toconfigure a new claim. In the Mapper Type, select the option “Authenticator”.

After all these configurations, as we can see in figure 4.5, it is possible to see the informationsent by Keycloak to the relying party, the name of the claim is “auth_type”, and the authenticatortype used to log in was X.509-client-certificate.

Page 82: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

60 Chapter 4. Testing and Results

Figure 4.4: Protocol mapper configuration to sent information about the authenticator type

Figure 4.5: Information about the authenticator type sent to the client as a token claim

4.4 Certificate X.509 provisioned in PKCS#11

4.4.1 IsoApplet

For our tests with smart cards we first installed OpenSC to manipulate it, seen in Section2.2.3.5. We use GlobalPlatformPro tool and library[53] that allows to load and manage appletson compatible JavaCard smart cards. We use this library to install IsoApplet in the smartcard and to be able to provision it with X.509 certificates. We did tests using Firefox (32 bits),

Page 83: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

4.4. Certificate X.509 provisioned in PKCS#11 61

Figure 4.6: Client certificate information obtained at the login time

because the version of XCA that we used to import keys and generate certificates is also 32 bits.To be able to authenticate with Mozilla Firefox it was necessary to add the OpenSC PKC§11Module in the browser, which provides access to smart card readers, biometric security devicesand external certificate stores.

The configuration to load a new module PKCS#11 in Mozilla Firefox was done as follows:Open the Firefox preferences dialog; click on “Privacy & Security”, scroll down and click“Security Devices”, click “Load”, then change the Module Name to module IsoApplet and selectthe installation directory, "C:/Windows/System32" (for Windows), "/Library/OpenSC/lib/"(for macOS), "/usr/lib/" (for Linux). Then select the opensc-pkcs11.dll (for Windows) oropensc-pkcs11.so (for Linux and macOS).

In order to associate the certificate data with the user, it is necessary to have the serviceresponsible for reading the certificate data installed on the smart card, by clicking on the “Load”button. Then the system requests the PIN, followed by a GET request that is generated toaccess the resource responsible for processing the business logic, reading the certificate data andreturning the SubjectDN and the Serial Number to associate the user, seen in the figure 3.14.

Once the subjectDN + serial Number is associated to the user, it can be authenticatedthrough the X509 client certificate the authentication process is the same as the one explainedabove.

4.4.2 Portuguese Citizen Card

For the purpose of testing the Portuguese Citizen Card "Cartão de Cidadão", first is necessaryto import the certificate chain from the Portuguese Citizen Card to the Keycloak truststore.

Page 84: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

62 Chapter 4. Testing and Results

After that, it is necessary to register the PKCS#11 module in Mozilla Firefox to be able toauthenticate in the websites using the Portuguese Citizen Card. Depending on the operatingsystem the location of the file is as follows:

Windows: C:/Windows/System32/pteidpkcs11.dll

Linux: usr/local/lib/pteidpkcs11.so

MAC OS: usr/local/lib/pteidpkcs11.bundle

As with IsoApplet, once the certificate data is associated with the user, it can be authenticatedvia X509 client certificate, the result obtained is the same explained in section 4.3, the onlychange is the procedure to read the certificate data.

It is important to mention that we strongly recommend using the PKCS#11 module indicatedin the Portuguese Citizen Card user manual, since we experience a lot of problems with theOpenSC module.

4.5 U2F Security Key

In the interest of testing the authentication through U2F devices, we use the ePass FIDO-NFCSecurity Key, which is a FIDO alliance certified U2F authentication key.

Firstly, if the type of authentication required is the U2F device, and in case that is notregistered, the user will be asked to register it, as seen in the figure 4.7, once it is registered, theinterface asks the user to touch the device as proof of possession, as seen in figure 4.8. It is alsopossible to associate the U2F device in the user account management, as represented in figure4.9.

Finally, regarding the type of authentication used by the user. In our test case, the U2Fdevice was used as a second factor, begin the username/password the a first factor, for thisreason its possible to see in the figure 4.10 that the two types of authenticators are sent into thetoken claim to the Relying Party.

4.6 Protocol Mapper

In order to send the information into the protocol claim, it is necessary to configure the mapperin the client configuration on the Keycloak administrator console, which allows sending datainto the token claim. In our case, we called "Authenticator" to the mapper type. Between theprotocol mapper options, it also possible to select where include or exclude the configured claimfrom the ID token, access token and/or user info only turning the corresponding buttons On orOff, seen figure 4.4.

As the protocol mapper is configured per client, and only once, the configuration per each

Page 85: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

4.6. Protocol Mapper 63

Figure 4.7: U2F Register request

Figure 4.8: U2F touch device request

authenticator provider is not necessary.

Page 86: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

64 Chapter 4. Testing and Results

Figure 4.9: U2F Register in user account management

Figure 4.10: In the claim auth_type, the authenticator type used to log in is sent. Theconfiguration is explained in section 3.6

4.7 Chapter summary

In this section, we make a summary of this chapter. In order to test our implementations, weuse an OpenID client "node-openid-client" and the browser Mozilla Firefox of 32 bits. We useMozilla Firefox of 32 bits in order to match the XCA and OpenSC architectures.

Throughout this chapter, we explained the system flow and the configurations that must be

Page 87: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

4.7. Chapter summary 65

made in Keycloak to use each authenticator provider available, from the procedure for creating auser to the configurations of the authenticator and the protocol mapper. Besides, we detailed thelibraries we used to interact with the smart card and a description of how to add the PKCS#11module in Mozilla Firefox.

Also, we present the results obtained with each authenticator type - additionally, we presentthe information sent to the relying party about the authentication method used at log in timeinto the protocol token claim, configured in authenticator protocol mapper.

Page 88: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais
Page 89: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Chapter 5

Conclusion

The theft of information as a whole has never been higher than it is now. Only in 2018 databreaches as Reddit[58], T-mobile[30, 69], only to mention a few notorious cases. One thing mostcases have in common, and how the Data Breach Investigations Report [73] shows is the lackof a strong authentication method and/or the existence of a weak password which could havebeen easily guessed. As an aggravating factor, when a particular platform enforces the usage of astrong password, it is also widely known that users tend to reuse the same password in multipleplatforms because for the user is hard to remember complex passwords.

As a matter of fact, the access to services through the Web is becoming increasingly commonwhich also means that amount of passwords a user must memorize is consequently increasing,and thus, it is important to emphasize that even though re-utilizing a password across severalplatforms is a bad idea, this practice is still very common due to being comfortable and easy forthe user.

Due to amount cases of Personally Identifiable Information (PII) data leaked on the Web,where even large corporations have fallen victims to such attacks, many corporations have decidedto implement more secure authentication methods. A secure alternative currently available is theTwo-Factor authentication (2FA), because it requires the user to submit a second factor to fullycomplete the authentication process, which makes the work of an attacker a lot harder, otherthan just trying to find the password by using dictionaries or frequent password databases. ,

Google has also experienced several phishing cases on individual user accounts and felt theurge to implementing their 2FA process to mitigate the risk. Google’s application to generateOne Time Password (OTP), so-called Google Authenticator - offers a more practical and cheaperoption and furthermore, less risky than using an SMS-based 2FA.

Nowadays, the SMS-based authentication is the most used way of 2FA authentication method.However, the National Institute of Standards and Technology (NIST) recommends not usingSMS-Based 2FA because of vulnerabilities as an out-of-band factor in multi-factor authenticationenvironments [20, 21].

67

Page 90: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

68 Chapter 5. Conclusion

When accessing sensitive or restricted data, is highly recommended a stronger or specificauthentication method, e.g., hardware-based authentication in order to keep the confidentialityof data protected and better restrict access only to the authorized party.

According to the content reviewed during the documentation of this thesis, all sources ofinformation (such as researchers, news, corporations, and regulatory agencies) have jointly agreedthat hardware-based authentication is one of the safest methods currently available. Google hasalso reported that no phishing cases have occurred since the hardware-based authentication keyhas been implemented [29, 39, 83].

Finally, we believe to have accomplished most of the pre-defined goals, failing to achieve onlyone "Process the required authentication type sent by the Relying Party for user re-authentication"which we decided to cover on future work. For now, the way we managed to reach this goal wasby forcing a user to re-authenticate and closing the session using the OIDC prompt=login URLparameter.

Even though some of the modules are still under development, all the testing performed canbe seen as the first step to a complete proof of concept. Keycloak continues to add new featuresand has recently launched in July the ThemeResourceProvider, which allows developers to addnew templates and resources without having to modify the default Keycloak classes. Modifyingall classes would have been a non-scalable solution, and therefore, we decided to discard thisapproach.

5.1 Future work

In the future, we plan to add new functionality to Keycloak, which will allow to process data fromthe Relying Party so that if the system needs a stronger authentication for certain transactions,the Relying Party can request Keycloak to re-authenticate the user with an additional type ofauthentication (stronger than the first one), including two-factor authentication.

We also plan to add more authentication methods and allow the user to manage all methodsthrough the user’s account console. Additionally, improving the authenticator selector that allowsthe user to choose their preferred authentication method to log in.

In term of authentication by X.509 client certificate, we plan to allow the user to create theirown certificate from the user’s console.

Regarding the import of the certificates to the truststore, it could be done automaticallythrough an API, at this moment it is necessary to import manually.

Page 91: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Bibliography

[1] Anne Adams and Martina Angela Sasse. Users are not the enemy. Communications of theACM, 42(12):40–46, 1999.

[2] FIDO Alliance. Fido2 project. Online, https://fidoalliance.org/fido2/ [visited September2018].

[3] Auteticação.GOV. Chave móvel digital. Online, https://www.autenticacao.gov.pt/a-chave-movel-digital [visited September 2018].

[4] Tom Barton, Jim Basney, Tim Freeman, Tom Scavo, Frank Siebenlist, Von Welch, RachanaAnanthakrishnan, Bill Baker, Monte Goode, and Kate Keahey. Identity federation andattribute-based authorization through the globus toolkit, shibboleth, gridshib, and myproxy.In 5th Annual PKI R&D Workshop, volume 4, 2006.

[5] Adobe Blog. Important customer security announcement. Online, https://theblog.adobe.com/important-customer-security-announcement/, March 2013 [visited July 2018].

[6] Joseph Bonneau, Cormac Herley, Paul C Van Oorschot, and Frank Stajano. The quest toreplace passwords: A framework for comparative evaluation of web authentication schemes.In Security and Privacy (SP), 2012 IEEE Symposium on, pages 553–567. IEEE, 2012.

[7] Scott Cantor and T Scavo. Shibboleth architecture. Protocols and Profiles, 10:16, 2005.

[8] Marcus A Christie, Anuj Bhandar, Supun Nakandala, Suresh Marru, Eroma Abeysinghe,Sudhakar Pamidighantam, and Marlon E Pierce. Using keycloak for gateway authenticationand authorization. 2017.

[9] D Cooper, S Santesson, S Farrell, S Boeyen, R Housley, and W Polk. Internet x. 509 publickey infrastructure certificate and crl profile. RFC5280, 2008.

[10] Jan De Clercq. Single sign-on architectures. In Infrastructure Security, pages 40–58. Springer,2002.

[11] Geoffrey B. Duggan, Hilary Johnson, and Beate Grawemeyer. Rational security: Modellingeveryday password use. International Journal of Human Computer Studies, 70(6):415–431,2012. ISSN: 10715819. doi:10.1016/j.ijhcs.2012.02.008.

69

Page 92: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

70 Bibliography

[12] Mete Eminagaoglu, Ece Cini, Gizem Sert, and Derya Zor. A two-factor authenticationsystem with qr codes for web and mobile applications. In Emerging Security Technologies(EST), 2014 Fifth International Conference on, pages 105–112. IEEE, 2014.

[13] Marlena Erdos and Scott Cantor. Shibboleth architecture draft v05. Internet2/MACE, May,2:33, 2002.

[14] W3C FIDO Alliance. Fido alliance and w3c achieve major standards milestone in globaleffort towards simpler, stronger authentication on the web. Online, https://www.w3.org/2018/04/pressrelease-webauthn-fido2.html.en [visited September 2018].

[15] Dinei Florencio and Cormac Herley. A large-scale study of web password habits. InProceedings of the 16th international conference on World Wide Web - WWW ’07, page 657,2007. ISBN: 9781595936547. doi:10.1145/1242572.1242661.

[16] OpenID Foundation. Openid. Online, http://openid.net/what-is-openid/, [visited June2018].

[17] The Apache Software Foundation. Apache freemarker manual. Online, https://freemarker.apache.org, [visited March 2018].

[18] Steven Furnell. Assessing website password practices–over a decade of progress? ComputerFraud & Security, 2018(7):6–13, 2018.

[19] Shirley Gaw and Edward W. Felten. Password management strategies for online accounts. InProceedings of the second symposium on Usable privacy and security - SOUPS ’06, page 44,2006. ISBN: 1595934480. doi:10.1145/1143120.1143127.

[20] Paul Grassi. Questions.. and buzz surrounding draft nist special publication 800–63–3. On-line, https://medium.com/@usnistgov/questions-and-buzz-surrounding-draft-nist-special-publication-800-63-3-5af0b7012374, July 2016 [visited March 2018].

[21] Paul A Grassi, JL Fenton, EM Newton, RA Perlner, AR Regenscheid, WE Burr, JP Richer,NB Lefkovitz, JM Danker, YY Choong, et al. Digital Identity Guidelines - Authenticationand Lifecycle Management . NIST Special Publication 800-63B, Revision 3(June):1–79, 2017.doi:10.6028/NIST.SP.800-63b.

[22] Red Had. Keycloak documentation. Online, https://www.keycloak.org/docs/3.3/server_admin/topics/authentication/x509.html [visited January 2018].

[23] Neil Haller, Craig Metz, Phil Nesser, and Mike Straw. A one-time password system. Technicalreport, 1998.

[24] Uwe Hansmann, Martin S Nicklous, Thomas Schäck, Achim Schneider, and Frank Seliger.Smart card application development using Java. Springer Science & Business Media, 2012.

[25] Dick Hardt. [OAuth 2.0] The OAuth 2.0 Authorization Framework [RFC 6749]. RFC 6749,pages 1–76, 2012. ISSN: 2070-1721. doi:10.1109/MIC.2012.11.

Page 93: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Bibliography 71

[26] John Hughes and Eve Maler. Security assertion markup language (saml) v2. 0 technicaloverview. OASIS SSTC Working Draft sstc-saml-tech-overview-2.0-draft-08, pages 8–9, 2005.

[27] WSO2 Inc. Wso2 identity server documentation. Online, https://docs.wso2.com/display/IS510/WSO2+Identity+Server+Documentation [visited November 2017].

[28] Internet2. Shibboleth. Online, https://www.internet2.edu/products-services/trust-identity/shibboleth/ [visited September 2018].

[29] Brian Krebs. Google: Security keys neutralized employee phishing. Online, https://krebsonsecurity.com/2018/07/google-security-keys-neutralized-employee-phishing/, July2018 [visited July 2018].

[30] Brian Krebs. T-mobile employee made unauthorized ‘sim swap’ to steal instagram account.Online, https://krebsonsecurity.com/2018/05/t-mobile-employee-made-unauthorized-sim-swap-to-steal-instagram-account/, May 2018 [visited August 2018].

[31] Brian Krebs. Reddit breach highlights limits of sms-based authentication. On-line, https://krebsonsecurity.com/2018/08/reddit-breach-highlights-limits-of-sms-based-authentication/, August 2018 [visited August 2018].

[32] Katharina Krombholz, Peter Frühwirt, Thomas Rieder, Ioannis Kapsalis, Johanna Ullrich,and Edgar Weippl. Qr code security–how secure and usable apps can protect users againstmalicious qr codes. In Availability, Reliability and Security (ARES), 2015 10th InternationalConference on, pages 230–237. IEEE, 2015.

[33] Robert Künnemann and Graham Steel. Yubisecure? formal security analysis results for theyubikey and yubihsm. In International Workshop on Security and Trust Management, pages257–272. Springer, 2012.

[34] Leslie Lamport. Password authentication with insecure communication. Communications ofthe ACM, 24(11):770–772, 1981.

[35] Juan Lang, Alexei Czeskis, Dirk Balfanz, Marius Schilder, and Sampath Srinivas. Securitykeys: Practical cryptographic second factors for the modern web. In International Conferenceon Financial Cryptography and Data Security, pages 422–440. Springer, 2016.

[36] LastPass. Lastpass. Online, https://www.lastpass.com/ [visited June 2018].

[37] LastPass. Lastpass security notification. Online, https://blog.lastpass.com/2011/05/lastpass-security-notification.html/, May 2011 [visited June 2018].

[38] LastPass. Incident report: March 22nd, 2017. Online, https://blog.lastpass.com/2017/03/important-security-updates-for-our-users.html/, March 2017 [visited June 2018].

[39] Kif Leswing. None of google’s 85,000 employees have had their work accounts takenover in a year — and it’s because of a simple $20 product anyone can use. On-line, https://www.businessinsider.com/none-of-googles-employees-get-phished-because-of-yubikey-security-key-2018-7 [visited July 2018].

Page 94: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

72 Bibliography

[40] Kelly D Lewis and James E Lewis. Web Single Sign-On Authentication using SAML. Journalof Computer Science, 2:41–48, 2009. ISSN: 1694-0814.

[41] Rui Martinho. Poreid. Online, https://github.com/poreid/poreid [visited August 2018].

[42] Microsoft. Understanding digital certificates. Online, https://technet.microsoft.com/en-us/library/bb123848(v=exchg.65).aspx, May 2005 [visited February 2018].

[43] N.Sakimura M.Jones , J.Bradley. JSON Web Token(JWT). Internet Engineering Task Force(IETF), 2015. ISSN: 2070-1721. doi:10.17487/RFC7519.

[44] Robert Morris and Ken Thompson. Password security: a case history. Communications ofthe ACM, 22(11):594–597, 1979. ISSN: 00010782. doi:10.1145/359168.359172.

[45] D M’raihi, M Bellare, F Hoornaert, D Naccache, and O Ranen. Hotp: An hmac-basedone-time password algorithm. Technical report, 2005.

[46] David M’Raihi, Salah Machani, Mingliang Pei, and Johan Rydell. Totp: Time-basedone-time password algorithm. Technical report, 2011.

[47] Collin Mulliner, Ravishankar Borgaonkar, Patrick Stewin, and Jean-Pierre Seifert. Sms-based one-time passwords: attacks and defense. In International Conference on Detectionof Intrusions and Malware, and Vulnerability Assessment, pages 150–159. Springer, 2013.

[48] Kim Nguyen. Authentification and identification—taking the user into account. Datenschutzund Datensicherheit-DuD, 38(7):467–469, 2014.

[49] OpenID. Openid certification. Online, http://openid.net/certification/ [visited September2018].

[50] Oracle. Java documentation - enum types. Online, https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html, [visited March 2018].

[51] Oracle. Oracle documentation - keytool. Online, https://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html, [visited March 2018].

[52] David Oswald, Bastian Richter, and Christof Paar. Side-channel attacks on the yubikey 2one-time password generator. In International Workshop on Recent Advances in IntrusionDetection, pages 204–222. Springer, 2013.

[53] Martin Paljak. Globalplatformpro. Online, https://github.com/martinpaljak/GlobalPlatformPro, 2011 [visited September 2018].

[54] Sean Parkinson, Kathleen Moriarty, Michael Scott, Andreas Rusch, and Magnus Nystrom.Pkcs# 12: Personal information exchange syntax v1. 1. Technical report, 2014.

[55] V. Radha and D. Hitha Reddy. A Survey on Single Sign-On Techniques. Procedia Technology,4:134–139, 2012. ISSN: 22120173. doi:10.1016/j.protcy.2012.05.019.

Page 95: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

Bibliography 73

[56] Wolfgang Rankl and Wolfgang Effing. Smart Card Handbook: Fourth Edition. John Wiley& Sons, Ltd, 2010. ISBN: 978-0-470-74367-6.

[57] David Recordon and Drummond Reed. Openid 2.0: a platform for user-centric identitymanagement. In Proceedings of the second ACM workshop on Digital identity management,pages 11–16. ACM, 2006.

[58] Reddit. We had a security incident. here’s what you need to know. On-line, https://www.reddit.com/r/announcements/comments/93qnm5/we_had_a_security_incident_heres_what_you_need_to/, 2018 [visited August 2018].

[59] RedHat. Keycloak. Online, http://www.keycloak.org/, [visited November 2017].

[60] RedHat. Undertow. http://undertow.io/, [visited November 2017].

[61] Justin Richer and Antonio Sanso. OAuth 2 in Action. Manning Publications, 2017.

[62] N Sakimura, J Bradley, and M Jones. OpenID connect dynamic client registration1.0 incorporating errata set 1. URL http://openid.net/specs/openid-connect-registration-1_0.html, 2014.

[63] Richard Shay, Lorrie Faith Cranor, Saranga Komanduri, Adam L. Durity, Phillip (Seyoung)Huh, Michelle L. Mazurek, Sean M. Segreti, Blase Ur, Lujo Bauer, and Nicolas Christin.Can long passwords be secure and usable? In Proceedings of the 32nd annual ACMconference on Human factors in computing systems - CHI ’14, pages 2927–2936, 2014. ISBN:9781450324731. doi:10.1145/2556288.2557377.

[64] Filip Skokan. Node-openid-client. Online, https://github.com/panva/node-openid-client[visited June 2018].

[65] Tan Jin Soon. Qr code. Synthesis Journal, 2008:59–78, 2008.

[66] Sampath Srinivas, Dirk Balfanz, Eric Tiffany, and Alexi Czeskis. Universal 2nd factor (u2f)overview. FIDO Alliance Proposed Standard, pages 1–5, 2015.

[67] M Stamp. Information security: principles and practice, volume 11. 2011. ISBN: 0-471-73848-4. doi:10.1515/ling.1973.11.97.95.

[68] Elizabeth Stobert and Robert Biddle. The password life cycle: User behaviour in managingpasswords. pages 243–255, 2014.

[69] T-Mobile. T-mobile employee made unauthorized ‘sim swap’ to steal instagram account.Online, https://www.t-mobile.com/customers/6305378821, 2018 [visited August 2018].

[70] L. Tam, M. Glassman, and M. Vandenwauver. The psychology of password management: Atradeoff between security and convenience. Behaviour and Information Technology, 29(3):233–244, 2010. ISSN: 0144929X. doi:10.1080/01449290903121386.

Page 96: Authentication modules for K eycloak authentication servercracs.fc.up.pt/sites/default/files/Thesis_Daicy.pdf · Hoje em dia, as passwords ainda são o método de autenticação mais

74 Bibliography

[71] TeamsID. 100 worst passwords of 2017! the full list. Online, https://www.teamsid.com/worst-passwords-2017-full-list/, 2017 [visited April 2018].

[72] New York Times. Security firm offers to replace tokens after attack. Online, https://www.nytimes.com/2011/06/07/technology/07hack.html, June 2011 [visited June 2018].

[73] Verizon. 2018 data breach investigations report. Trends, pages 1–68, 2018.

[74] Rick Wash, Emilee Rader, Ruthie Berman, and Zac Wellmer. Understanding PasswordChoices : How Frequently Entered Passwords Are Re-used across Websites. Proceedings ofthe Twelfth Symposium on Usable Privacy and Security (SOUPS 2016), (Soups):175–188,2016.

[75] Philip Wendland. Isoapplet. Online, https://github.com/philipWendland/IsoApplet [visitedSeptember 2018].

[76] Petra Wohlmacher. Digital certificates: a survey of revocation methods. Proceedingsof the 2000 ACM workshops on Multimedia, pages 111–114, 2000. ISSN: 1581133111.doi:10.1145/357744.357892.

[77] Tzu-I Yang, Chorng-Shiuh Koong, and Chien-Chao Tseng. A cross-idp single sign-on methodin saml-based architecture. In Future Information Technology, pages 63–68. Springer, 2014.

[78] Yuha Yrjölä and Timo Teräs. Opensc. Online, https://github.com/OpenSC/OpenSC//[visited September 2018].

[79] Yubico. Fido2. Online, https://www.yubico.com/solutions/fido2/, [visited September 2018].

[80] Yubico. Otps explained. Online, https://developers.yubico.com/OTP/OTPs_Explained.html, [visited August 2018].

[81] Yubico. What is u2f? Online, https://developers.yubico.com/U2F, [visited August 2018].

[82] Yubico. Fido u2f. Online, ://www.yubico.com/solutions/fido-u2f/, [visited August 2018].

[83] Yubico. Google defends against account takeovers and reduces it costs. https://www.yubico.com/about/reference-customers/google/, [visited September 2018].

[84] Yubico. The yubikey manual version: Usage, configuration and introduction of basicconcepts (version 3.4). Online, https://www.yubico.com/wp-content/uploads/2015/03/YubiKeyManual_v3.4.pdf, March 2015 [visited August 2018].