MASARYK U N I V E R S I T Y FACULTY OF INFORMATICS Safety Widget Master's Thesis TOMÁŠ PSOTA Brno, Fall 2023 MASARYK U N I V E R S I T Y FACULTY OF INFORMATICS Safety Widget Master's Thesis TOMÁŠ PSOTA Advisor: prof. RNDr. Tomas Pitner, Ph.D. Department of Computer Systems and Communications Brno, Fall 2023 Declaration Hereby I declare that this paper is m y original authorial work, which I have worked out o n m y o w n . A l l sources, references, a n d literature used or excerpted during elaboration of this work are properly cited and listed i n complete reference to the due source. Tomáš Psota Advisor: prof. R N D r . Tomáš Pitner, P h . D . iii Acknowledgements I w o u l d like to thank my supervisor, prof. R N D r . Tomas Pitner, Ph.D., for his valuable advice and helpfulness during the elaboration of the thesis. Special thank you goes to the employees of Lynx SFT s.r.o. and A h e a d iTec s.r.o, especially to Ondfej P f i k r y l and Julia Gonova, for their helpful advice and time invested into consultations. I w o u l d also like to express my gratitude to my friends and family for their support during m y studies. iv Abstract This thesis introduces the Safety Widget, an app a d d - o n designed to address the absence of standardized security markers i n the mobile app ecosystem. In response to the prevalent shift towards mobile-first development, the Safety Widget serves as a dynamic element providing real-time insights into the security status of a mobile application. With a focus on enhancing the trust of the users and bridging the gap between application complexity and ease of use, the a d d - o n offers customizable visual elements, predefined threat reactions, detailed security check summaries, and robust localization support. The Safety Widget is written using the Flutter framework and is available for A n d r o i d and iOS. In the theoretical part, the thesis justifies the choice of Flutter for development and explains the core concepts of mobile app security. The R A S P technology is described, along with freeRASP, a security library providing thorough app security audit. The practical part describes the implementation of the Safety Widget in Flutter. The final outcome is a working Flutter package that can be integrated into any Flutter mobile application. Keywords Flutter, Dart, security, RASP, mobile application, Flutter package v Contents 1 Introduction 1 2 Safety Widget 3 2.1 Functional requirements 3 2.2 Non-Functional requirements 4 2.3 Programming language 5 3 Flutter 7 3.1 Flutter characteristics 8 3.2 Dart 9 3.3 Packages i n Dart 10 3.4 Communication of Flutter w i t h Native code 12 3.4.1 Lifecycle of Flutter plugins 13 3.4.2 Plugin registration w i t h i n Flutter Engine . . . . 14 3.4.3 Flutter Engine 15 4 Mobile security 16 4.1 O W A S P 16 4.1.1 O W A S P Mobile Application Security 16 4.1.2 O W A S P M A S V S 17 4.1.3 O W A S P M A S T G 19 4.1.4 Most common mobile app security threats . . . 19 4.2 R A S P 22 4.2.1 freeRASP 24 5 Design choices 29 5.1 Global state management 29 5.1.1 Choosing the right framework 31 5.2 Starting the freerasp p l u g i n 32 5.3 Customization 33 5.4 Local storage 34 6 UX/UI 36 6.1 Provided design 36 6.1.1 Similarities w i t h the CybeTribe 36 6.2 Design extension 37 vi 6.2.1 Dark mode 37 6.2.2 Layout options 38 6.2.3 Safety Widget icon 39 7 Implementation 40 7.1 Third-party dependencies 40 7.2 State management 42 7.3 Styling 44 7.4 Localization 46 7.5 Launching the app 47 7.6 Additional reactions to threats 51 7.7 Integration into an app 53 8 Widget Testing and Validation 57 9 C o n c l u s i o n 59 9.1 Future work 60 A Electronic attachments 65 B Safety Widget Snapshots 66 vii List of Figures 3.1 Dart compilation process based o n the target platform. . . 10 3.2 Visualization of Dart Platform channels 13 5.1 Visualization of application start 33 5.2 Local storage architecture 35 6.1 Security A u d i t page i n CybeTribe serving as a starting point for the dark mode 37 6.2 Design of a recommendation page f r o m the CybeTribe app, resembling dark mode 38 7.1 The ThreatController class 43 7.2 The _runMainApp() method responsible for starting the app 44 7.3 The theme extension for providing the extra flexibility missing i n the default ThemeData 46 7.4 A part of the translation of the texts 47 7.5 The process of starting the app 49 7.6 The default splash screen of Safety Widget 50 7.7 The class allows to a d d additional reactions for threats detected by freerasp 52 7.8 The predefines additional actions provided by Safety W i d get 53 B . l Safety Widget running o n a smaller 4.7" Galaxy Nexus 4 w i t h the Home page layout option i n both light a n d dark modes 66 B.2 Safety Widget running on a Google Pixel 6 with the Bottom navigation layout option i n both light a n d dark modes. . . 67 B.3 Safety Widget running on an iPhone 14 Pro with the Home page layout option i n dark mode 68 B.4 Safety Widget running o n a Google Pixel 4 w i t h the Chip menu layout option i n both light a n d dark modes 69 B.5 Safety Widget running on a Google Pixel 5 w i t h the Compact layout option i n dark mode 70 B.6 The localized version of the Safety Widget. The titles on the Galaxy Nexus 4 (bottom row) are slightly smaller to fit on the screen 71 viii B.7 The optional reactions to threats. In the figure, a native alert is displayed o n the device for i O S (left) as CupertinoAlert and A n d r o i d (right) as MaterialAlert 72 B.8 The default splash screen that can be used while the app is waiting for the completion of the freerasp's security audit. 73 ix 1 Introduction In recent years, there has been a significant change f r o m desktop to mobile [1]. Consequently, many companies are shifting to mobile- first1 development of their applications. However, unlike the web, one crucial aspect often remains hidden for the app users: security. In contrast to the web app world, with its familiar symbols indicating the app's security like the lock icon i n the address bar signifying secure connection, the app ecosystem lacks such standardized markers. This discrepancy represents not only a challenge but also a compelling opportunity for innovation. These facts empower the concept of the Safety Widget, an app a d d on designed to empower app users and establish itself as the beacon of security i n the world of mobile apps. The Safety Widget is a dynamic element of a mobile app that provides real-time insights into the security status of a particular app on a specific device precisely when the user needs it. It is a clickable widget that offers users guarantees about specific aspects of mobile security a n d serves as a gateway to comprehensive safety-related information. Safety Widget allows to review an app's security at the app's runtime, all w i t h a simple tap o n a Safety Widget's icon. It is designed to improve the reputation a n d earn the users' trust of the apps, as it provides immediate response to detected threats or missing safety features of the device. By integrating Safety Widget into an app, companies a d d an additional layer that protects their users from fraud. In a world where cyber threats continue to evolve, Safety Widget bridges the gap between the developer world's complexity a n d the user's desire for clarity and simplicity. The widget tries to create a safer and more informed app ecosystem. It enables users to make betterinformed choices a n d companies to improve security a n d trust. The security of mobile apps was underrated for a long time, w h i c h often resulted i n loss of revenue or user dissatisfaction. Safety Widget aims to improve users' knowledge about mobile security, inform them about the security state of their devices a n d apps, a n d serve as a source of competitive advantage and brand integrity. In the first phase that w i l l 1. A "mobile-first" approach focuses primarily on the mobile version of an application, which is later adapted to larger screens 1 i . I N T R O D U C T I O N be implemented as a part of this thesis, the initial version of the Safety Widget w i l l be created. 2 2 Safety Widget This chapter explains the requirements that must be satisfied by the implementation of the Safety Widget. A l s o , the chapter covers the choice of the programming language used for the development. 2.1 Functional requirements The following is a summary of requirements for the functionality of the Safety Widget, divided into logical parts. • Widget icon The widget w i l l indicate the security state directly i n its icon via a circular state indicator, without having to open the widget itself. Internally, it must integrate freeRASP, a security S D K explained i n further chapters. The widget w i l l have three states: - Loading - the state is shown between app startup and up to a moment w h e n all checks of freeRASP are completed, - Success - the state shown after all checks of freeRASP are completed, and no threat callback was triggered, - Failure - the state is shown after all checks of freeRASP are completed and at least one threat callback was triggered. After tapping the icon, a new screen must appear: either w i t h a summary, bottom menu, or plain security check page. • Widget icon modifications Developers integrating the p l u g i n must be able to change the visual side of the widget; they must be able to change its size and base color of the widget to match their specific needs. • Reactions to threats The widget must have predefined reactions to threats; w h e n a threat callback is received, the Safety Widget must change its state to Failure and flag the threat as detected i n the threat details page. In addition, developers may choose to terminate the application, w h i c h must be handled by the widget as well. 3 2. SAFETY W I D G E T • Results of freeRASP checks After the Safety Widget is opened, it must display a summary of the checks that were performed. Furthermore, users must be able to access details about the state of each individual check. • Description of performed checks The user must be able to access a description of the performed check easily. • Localization The Safety Widget is intended to be used worldwide; therefore, it must provide robust support for localization to ensure that it can be adapted to various languages, regions, and other specific preferences. This functionality is essential to enhance the user experience and accessibility of the app for a global audience. 2.2 Non-Functional requirements The following is a summary of requirements for the functionality of the Safety Widget, divided into logical parts. • Widget icon The widget must conform to the p r o v i d e d visuals and must contain an indicator w i t h the security state displayed i n the lower left corner. This indicator w i l l have three variants: - Loading indicator - represented by a blue circle w i t h a white circular loading indicator, - Success indicator - represented by a green circle w i t h white checkmark, - Failure indicator - represented by a red circle with a white exclamation mark. • Usability The widget must be easy to use and navigate. A l s o , it must follow its m a i n purpose, w h i c h is getting i n touch w i t h the app's security i n a non-technical way. 4 2. SAFETY W I D G E T • Extensibility A s there are plans for Safety Widget extension i n the future, the code must be structured properly and adaptable to changes without requiring a complete redesign. • Security To provide as m u c h protection as possible, the widget must start the freeRASP and trigger the checks automatically while the app is being initialized. • D i s t r i b u t i o n It must be possible to u p l o a d Safety Widget to P u b . d e v 1 and distribute it as a standard Flutter dependency, w h i c h can be installed v i a standard Flutter C L I , i.e., v i a f l u t t e r pub add command. • Package size Because the Safety Widget is intended to be a custom Flutter widget, the final package size must be minimal and not use too many custom assets to avoid unnecessary growth i n the final app's size. • Documentation The project must be thoroughly documented, and an integration manual w i t h detailed steps explaining h o w to integrate the Safety Widget into an app must be created. • Other dependencies A l l dependencies of the Safety Widget must be licensed under a permissive2 type of license, as are M I T or Apache licenses. 2.3 Programming language The choice of a framework used for Safety Widget implementation was taken collectively i n Talsec i n multiple steps. 1. The package manager for the Dart programming language: https://pub.dev 2. A type of license that makes only minimal restrictions on how the software can be used, modified, and redistributed. It is often called BSD-like or BSD-style license, as well. 5 2. SAFETY W I D G E T Firstly, it was determined that time to market is crucial. Because native development requires the implementation of the functionality separately for A n d r o i d and iOS, it takes a longer time to develop a native app, or more developers and expertise are needed compared to multi-platform frameworks. Therefore, a multi-platform approach was chosen as the most suitable variant for the Safety Widget. After that, a multi-platform framework had to be chosen. In Talsec, four multi-platform frameworks support the freeRASP security library: Flutter, React Native, Cordova and Capacitor. Based on the data from Talsec, Cordova and Capacitor were ruled out due to their lower popularity i n comparison w i t h the other two. Based on the restrictions given by the project, both frameworks were almost equally appropriate. Both of them support A n d r o i d and iOS platforms, are highly popular, support hot reload, and have a large ecosystem of third-party libraries. The Safety Widget has its custom theme, w h i c h mitigates one of the m a i n advantages of React Native: native app feel. Both JavaScript used by React Native and Dart used by Flutter are languages already in use i n Talsec, so none can be preferred due to lack of knowledge. Ultimately, one of the critical aspects that made a difference was time to market. The speed of development proved to be faster i n Flutter. Also, current trends hint that Flutter's popularity is increasing, whereas React Native's is decreasing. Considering all of this, it was decided that the Safety Widget w o u l d be written primarily i n Flutter. 6 3 Flutter Flutter is an open-source framework developed by Google that gained popularity due to its ability to b u i l d natively compiled applications that r u n on multiple platforms under a unified codebase. With that, it significantly reduces the development time, as well as the final cost of the application [2]. A t the core of a Flutter application is the widget, the m a i n building block of a Flutter app. The importance of widgets i n Flutter is nicely illustrated by the phrase Everything is a Widget, w h i c h became very popular among the Flutter developer community and nowadays symbolizes the pivotal role of widgets i n the language. It emphasizes that i n Flutter, everything, including the user interface components, layouts, and even the application itself, is represented as widgets [3]. Generally, widgets serve as building blocks for constructing complex user interfaces. They offer flexibility for customization to meet specific needs and can be combined to form new widgets. Conceptually, they are similar to components i n React. The Flutter framework provides a large variety of widgets available v i a many standard components that cover all basic needs for building an application [2]. The most popular widgets can be searched for i n the official Widget Catalog1 . In addition, Flutter widget index2 offers a list of almost every publicly available widget that can be used i n the Flutter framework. Since Flutter was first presented at the 2015 Dart developer summit under the name Sky [2], i n just eight years, it has emerged as one of the leading frameworks for mobile development. Various research studies, such as those by Statista3 and StackOverflow Developer Surv e y 4 , point out that it recently surpassed the previous leader, React Native. Additionally, these studies indicate higher developer satisfaction w i t h Flutter compared to other frameworks currently used for 1. https://docs.flutter.dev/ui/widgets 2. https://docs.flutter.dev/reference/widgets 3. https: / /www.statista.com/statistics/1326121 /top-app-dev-engines- worldwide/ 4. https://survey.stackoverflow.co/2023/most-popular-technologies-misc-tech 7 3. FLUTTER mobile development. 3.1 Flutter characteristics Besides the already mentioned single codebase, Flutter features several other important characteristics highly appreciated by the developer community [4]. Following are the most significant advantages of Flut- ter: • Hot reload A feature i n Flutter that allows developers to instantly see the results of code changes without the need to rebuild the whole application. This feature thus makes the development process faster and more efficient. • Performance Flutter compiles to native ARM code for mobile devices, resulting i n high-performance applications that can match the performance of natively developed apps [5]. • Design systems Flutter provides out-of-the-box support for both Material Design (Google's design language) a n d Cupertino (Apple's design language for iOS), making it easy to create platform-specific UIs that have a pleasant look o n both platforms. • Integration and plugins Flutter integrates well w i t h various backend services, databases, and third-party APIs through plugins. There is a wide selection of plugins available for accessing device features. • Community Flutter's ecosystem is continually growing, providing a w i d e range of packages, plugins, and extensions available for building an application. Besides this, Flutter maintains an active update cycle and continues to enhance its features. 8 3. FLUTTER 3.2 Dart Dart is an object-oriented programming language developed by Google It was initially created to provide an alternative to JavaScript for web development. It should have addressed the shortcomings of JavaScript in terms of performance, scalability, and maintainability However, it did not prove itself i n this area and rather found its usage elsewhere, most notably as the p r o g r a m m i n g language for b u i l d i n g user interfaces w i t h the Flutter framework [6]. Dart first appeared i n October 2011. In 2015, the Dart developers dropped the initial idea and fully focused on integrating w i t h Flutter for mobile apps and compiling Dart into Javascript for web [1]. Dart distinguishes two types of compilation processes, where the difference depends on the intended platform of the build: • Dart Native w i l l be used for the code that is intended for mobile or desktop. It compiles the code onto ARM or x86_64 architectures using Dart VM w i t h one of the two available compilers, depending on the current setup. The just-in-time (JIT) compiler w i t h incremental recompilation w i l l be used during the development phase of the app to enable developers to progress faster, support features like H o t reload and make debugging easier. The Dart ahead-of-time (AOT) compiler w i l l be used when the app is ready to be deployed into production. In comparison w i t h the JIT compiler, the startup time of the app is shorter and more consistent. This code is executed w i t h i n a Dart runtime, w h i c h enforces the sound Dart type system and handles memory management using fast object allocation and a generational garbage collector [2]. • Dart Web w i l l be used for web applications. Dart w i l l compile into JavaScript v i a the dartljs compiler, m a k i n g it possible to run the compiled Dart code i n web browsers. It also has two compiling options: a development compiler for faster development and a production compiler w i t h optimized JavaScript code [2]. 9 3. FLUTTER Dart code Target platform Compiler Dart ACT/ Dart JIT Figure 3.1: Dart compilation process based o n the target platform. 3.3 Packages in Dart To make code reusable i n different projects and easy to share, Dart uses a concept of packages. The packages provide additional functionality that can be shared o n p u b . d e v 5 , a n official Dart package repository. Dart packages can also be installed from a local source or a git repository. A list of installed packages is s h o w n i n pubspec.yaml file as the project's dependencies. These are installed via pub package manager [7], which also handles the package's versions and compatibility w i t h other installed packages [6]. A minimal package consists of a pubspec.yaml file and a lib folder. The pubspec.yaml declares the basic information about the package, including its name, author, remote repository, metadata, and others. The lib folder contains the implementation of the package, including at least one .dart file. W h e n developing a Flutter extension, developers must make an important design decision before starting the p l u g i n development: whether the plugin needs to access native A n d r o i d A P I or native iOS A P I , or whether it w i l l be enough to write it i n Dart exclusively [8]. 5. https://pub.dev/ 1 0 3. FLUTTER Based on this decision, p l u g i n developers can choose between the following options: • Dart packages The most basic type among the three options. The code is written entirely i n Dart, keeping the complexity l o w and m a k i n g testing easier. They do not contain native functionality and do not have access to the device's native parts and modules [2]. • Plugin packages These are also often referred to as Flutter plugins. Similarly to Dart packages, they include some Dart code that provides specific functionality to the outer application. However, it also enables the p l u g i n developer to write some of the code i n the platform-specific language, for example, i n Java or Kotlin for A n d r o i d and Objective-C or Swift for iOS. D u e to access to native code, it is also possible to access the device's sensors and modules. There are several advantages of developing specific parts of the module i n native code, including faster code execution due to better code optimization or reusing native code written previously to save resources and time [2]. • FFI Plugin packages The FFI stands for Foreign Function Interface; this plugin bridges the functionality of existing native libraries written i n C and exposes their interface i n Dart [9]. The implementation part of the thesis is a Dart package. This is the most suitable option due to better optimization and because the i m plementation does not have to touch the native code. The choice was justified i n Talsec to ensure that this decision w o u l d not negatively affect the project i n the future. It was decided that if there were a requirement to modify the native code, it w o u l d be handled through an external plugin, which w o u l d then expose the required A P I to the Safety Widget. 11 3. FLUTTER 3.4 Communication of Flutter with Native code Because Flutter's design allows access to native code, it is necessary to provide some f o r m of communication between these two parts. A l t h o u g h Safety Widget does not use this type of communication d i rectly, some of its dependencies communicate with the native platform, w h i c h w i l l be explained i n future chapters. The communication is achieved via channels that serve as a communication tool to send and receive messages i n a platform-specific6 way from Flutter to native code, and vice versa. To keep things organized, there are multiple types of channels that serve a slightly different purpose. However, all the channels are commonly referred to as Platform channels. In both directions, the messages are encoded into binary format for security reasons. Each Platform channel has to have its name, w h i c h is specified w h e n the channel is being initialized. This helps to distinguish the messages sent i n specific channels from messages belonging to another channel [8]. There are three types of Platform channels available: 1. BasicMessageChannel The simplest f o r m of a Platform channel. It is used to send basic messages into native code asynchronously. W h e n being initialized, it requires the type of message codec as a parameter, that is used to encode and decode the messages. The BasicMessageChannel requires the receiver (either on the Dart or native side) to respond w i t h at least a null value so that it can complete the Dart future replies [10]. 2. M e t h o d C h a n n e l For this channel type, the most c o m m o n use case is calling native APIs. First, i n Flutter code, a native method is called. After that, the call is sent over the Method channel to the native platform, which listens for the messages. Then, the code of the native method is executed asynchronously, and if there is any result, it is sent back to Flutter as a response. W h e n there are multiple calls performed simultaneously, it is guaranteed that the first request is served first [11] 6. The channels are designed and implemented in a manner specific to Android and iOS platforms. 12 3. FLUTTER 3. EventChannel Used w h e n it is necessary to keep the connection open for listening to events that may occur over a certain period of time. Such events may include retrieving battery status, accessing data from the device's sensors, or changing the device state. To create an Event channel instance, it is necessary to implement the FlutterStreamHandler interface i n the native code. The interface has three methods: o n L i s t e n O , w h i c h is called w h e n the channel is opened; onPause (), called w h e n the channel is paused, i.e., w h e n the app is moved to the background; and onCancel (), used w h e n the channel is closing. For the initialization of the channel, it is necessary to use the same name for the channel on the native and Dart sides. The events are then consumed v i a receiveBroadcastStream method of the Event channel. It is also possible to send events i n the other direction via the invokeMethod() method. [12] iOS Flutter Engine Figure 3.2: Visualization of Dart Platform channels. 3.4.1 Lifecycle of Flutter plugins Similarly to an application as a whole, plugins also have their lifecycle, defining how they are handled from startup until teardown. Starting f r o m the initialization, there has to be a runner responsible for executing the code. To start a Flutter Plugin, it is necessary 13 3. FLUTTER to register it w i t h i n a Flutter Engine, w h i c h is responsible for setting up platform channels, painting the Flutter U I , and executing the Dart code. It is possible to have multiple instances of Flutter Engine i n a single application. W h e n a p l u g i n is added to a Flutter application, the plugin is bound to a specific instance of the engine. A plugin must wait until it is fully attached, and only after that can it execute its code, w h i c h happens w h e n the onAttachedToFlutterEngine () method is completed. This process is performed automatically via GeneratedPluginRegistrant class, which implements the PluginRegistry interface. The interface contains multiple methods for managing plugins [13]. When a plugin is attached to FlutterEngine instance, it gains access to methods on resources within the F l u t t e r P l u g i n B i n d i n g , including Context of the application7 , Flutter Binary messenger, and Flutter Assets8 . After obtaining the messenger, it is possible to register a Method channel to set up communication between Flutter and the native platform [14]. When the app is closing, it is necessary to remove all links with the native platform and inform the plugin about the app's teardown. These events are triggered w h e n the FlutterEngine instance is destroyed, or the plugin is removed via the remove () method. In both cases, the FlutterEngine w i l l invoke the onDetachedFromEngine ( F l u t t e r P l u g i n B i n d i n g ) method on the given Flutter plugin. Then the method completes, and the plugin loses all access to F l u t t e r P l u g i n . F l u t t e r P l u g i n B i n d i n g [13]. 3.4.2 P l u g i n registration w i t h i n Flutter Engine FlutterEngine is the sole operational environment for Flutter, w h i c h acts as a container for executing Dart code within the supported platforms. Within a FlutterEngine, Dart code can run independently i n the background or be displayed on the screen using the accompanying FlutterRenderer. It achieves this by utilizing Dart code alongside the Flutter framework on the Dart side. The rendering process can be initiated and halted, allowing a FlutterEngine to transition from user interface interaction to exclusive data processing and back to user interface interaction as needed [2]. W h e n the first FlutterEngine is instantiated in a process, it also loads the native library of the FlutterEngine and initiates the Dart V M . Subsequent FlutterEngine instances w i l l r u n on 7. Interface to global information about an application environment. 8. Utility interface that provides the file path to the specified Flutter asset. 14 3. FLUTTER the same V M instance, but w i l l have their o w n Dartlsolate w h e n the DartExecutor is executed. Each Isolate works as an isolated Dart environment and can only communicate w i t h others through the Isolate ports [8]. 3.4.3 Flutter Engine The FlutterEngine instance maintains information about all the registered plugins and offers methods for accessing their functionality. A m o n g these methods is a method g e t P l u g i n s O , w h i c h returns a plugin registry object that implements the P l u g i n R e g i s t r y interface. This object contains information about all plugins attached to the specific FlutterEngine instance [15]. Typically, Flutter manages the added plugins automatically, and manual configuration is not required. However, since the plugin registry is accessible, it is also possible to manage the plugins directly using the provided registry methods. These methods for handling plugins include [16]: • v o i d a d d ( F l u t t e r P l u g i n p l u g i n ) This method adds the specified plugin to the plugin registry. • boolean has(Class p l u g i n C l a s s ) This method checks if the specified p l u g i n C l a s s matches any plugin i n the registry and returns true if it finds a match. • v o i d remove(Class p l u g i n C l a s s ) This method removes the plugin that matches the p l u g i n C l a s s class. • v o i d r e m o v e A l l O This method removes all the plugins attached to the engine. 1 5 4 Mobile security Mobile security, often overlooked i n the digital world, is more important than ever. The threats aimed at mobile privacy are becoming more sophisticated, m a k i n g it trickier for users to spot them. This chapter serves as an introduction to the world of mobile security, elaborating on the most common threats with O W A S P for mobile, explaining how the threats can be mitigated w i t h the use of R A S P technology, and closely inspects an implementation of R A S P distributed as a Flutter plugin. 4.1 OWASP The Open Worldwide Application Security Project (OWASP1 ) is a community of security enthusiasts that actively creates and shares a wide range of unpaid content, including articles, methodologies, documentation, tools, and technologies related primarily to web application security. O W A S P ' s mission is to provide open resources i n the field of security. The O W A S P Foundation, a non-profit organization, leads these efforts [17]. One of OWASP's notable contributions is the OWASP Top 10, a publication synthesizing data collected from over 40 collaborating organizations2 . It was first published i n 2003 and is updated regularly to match the current trends [18]. Besides its m a i n focus on the web, it also has extensive materials related to mobile, such as O W A S P Mobile Application Security. 4.1.1 OWASP Mobile Application Security The primary goal of the O W A S P Mobile Application Security (MAS) project is to provide the expertise required to b u i l d secure mobile applications. It offers an established security benchmark for mobile applications in the form of O W A S P Mobile Application Security Verification Standard (MASVS3 ) and a thorough testing manual k n o w n as 1. https://owasp.org/ 2. https:/ /owasp.org/www-project-top-ten/ 3. https://mas.owasp.org/MASVS/ 16 4- M O B I L E SECURITY O W A S P Mobile Application Security Testing Guide (MASTG*). These resources provide comprehensive information about the methods, approaches, and tools applied i n mobile app security assessments, alongside an extensive suite of test cases that allow testers to ensure their results are both consistent and comprehensive [19]. The organization also maintains OWASP Mobile Top 10, a document that points out the most c o m m o n vulnerabilities i n mobile application security The document is updated regularly to reflect recent trends i n the industry. It is a mobile equivalent of the web variant, OWASP Top 10. Overall, the M A S project aims to define the industry standard and raise awareness of mobile application security [20]. 4.1.2 OWASP M A S V S The O W A S P M A S V S is a resource for mobile software architects and developers w h o want to b u i l d secure mobile applications. Furthermore, it helps security testers maintain the integrity and thoroughness of their test cases. The M A S V S covers multiple aspects related to mobile development: storage, cryptography, authentication and authorization, network communication, platform interaction, code quality, and resilience against reverse engineering and tampering. A l l of these categories are aimed at the security of the client-side part of the mobile app [21]. O W A S P recommends evaluating the compliance of a mobile app w i t h the M A S V S v i a an open-book review, where the testers are prov i d e d w i t h access to key resources such as project documentation, source code, and authenticated access to endpoints, including access to at least one user account for each role. The SafetyWidget implemented as a part of this thesis fulfills the resilience requirements of O W A S P M A S V S . This is achieved by i n tegrating the f reerasp package for Flutter, w h i c h provides controls required by M A S V S . Specifically, these are: 1. MASVS-RESILIENCE-1: The app validates the integrity of the platform This requirement aims to verify the integrity of the operating system, ensuring that it has not been compromised and that 4. https://mas.owasp.org/MASTG/ 17 4- M O B I L E SECURITY its security features remain trustworthy W h e n a platform has been tampered with, it may possess a security risk as some of the security features may be disabled, or there may be improper handling of user's data [22]. 2. MASVS-RESILIENCE-2: The app implements anti-tampering mechanisms Applications operate on devices under the user's control, and in the absence of adequate safety measures, there is a relatively simple opportunity for local modification or the potential to upload a tampered version to unofficial app marketplaces. This control safeguards the app's intended functionality by restricting modifications to its original code and resources [23]. 3. MASVS-RESILIENCE-3: The app implements anti-static analysis mechanisms Understanding the code is usually the first step to app tampering. W h e n the app cannot be analyzed statically, or at least it is hard to do so, it makes it n o n - t r i v i a l task for an attacker to understand the code and modify it. W h e n this requirement is satisfied, analyzing the code via static analysis tools should not have a satisfactory outcome. A s a result, this requirement increases the security of the app [24]. 4. MASVS-RESILIENCE-4: The app implements anti-dynamic analysis techniques Because static analysis can be challenging and time-intensive, it is often complemented by dynamic analysis. Observing and interacting w i t h an application during runtime significantly simplifies understanding what it actually does. This security measure is designed to maximize the difficulty of performing dynamic analysis and to block dynamic instrumentation, which could potentially enable an attacker to modify the code while the application is running [25]. The SafetyWidget automatically scans the underlying application based on the provided configuration. W h e n the configuration does not match with what was provided, it is a sign of app tampering, resulting in breaking the app's integrity. In that case, the app is immediately 1 8 4- M O B I L E SECURITY notified and can take appropriate actions; for example, the app can be terminated. In addition, the Safety Widget can inform the developer about missing obfuscation. Obfuscating the source code dramatically increases the app's complexity, m a k i n g it hard for analysis tools to understand the code. W i t h these measures, the SafetyWidget fulfills the MASVS-RESILIENCE-1 and MASVS-RESILIENCE-2 requirements. Furthermore, it helps to fulfill the MASVS-RESILIENCE-3 and MASVSRESILIENCE-4 requirements by checking if the code is obfuscated. 4.1.3 O W A S P M A S T G The O W A S P M o b i l e Application Security Testing G u i d e is a comprehensive resource that provides guidance, best practices, technical processes, and tools for verification of implemented measures required by O W A S P M A S V S . It covers various aspects of mobile app security, including threat modeling, security architecture, authentication, data storage, network communication, and more. The guide is intended to help developers, security professionals, and testers assess and enhance the security of mobile applications to protect against c o m m o n vulnerabilities and security threats [26]. 4.1.4 Most common mobile app security threats Mobile app security threats present significant risks to personal i n formation, financial data, and often identities of the users. From data breaches and unauthorized access to the presence of third-party app stores and unverified downloads, there is a diverse range of risks that developers and organizations must account for while evaluating the state of their mobile app security. Protecting from the most c o m m o n smartphone threats as a preventive measure can help users gain trust, keep satisfaction w i t h the services high, and prevent any revenue or reputation losses. This section presents the security vulnerabilities that are most commonly present i n mobile apps and are often abused by attackers. The OWASP Mobile Top 10 lists the most frequent threats that mobile apps are facing [20]. Its last final list was released i n 2016. However, there is also an updated list w i t h threats updated i n 2023. It contains 1 9 4- M O B I L E SECURITY 10 threats, ordered by their importance, where number 1 is the most significant threat. Each threat is thoroughly described and mentions various aspects, as threat agents (who or what presents the threat), attack vectors, security weaknesses, technical and business impacts, and example attack scenarios. In addition, each threat contains a checklist that helps to identify if the threat is present i n the app and recommendations on h o w to prevent the threat. The 2023 list is labeled as an initial release; therefore, it may still change until it is finalized. A s the last final release is already seven years o l d at the time of writing this thesis, the preliminary 2023 OWASP Mobile Top 10 w i l l be analyzed. According to the list, the most c o m m o n threats are [20]: 1. M l : Improper Credential Usage The threat describes bad coding practices w i t h sensitive data, including hardcoded credentials, insecure credential storage, and weak user authentication. 2. M2: Inadequate Supply Chain Security This vulnerability is related to leveraging weaknesses i n the mobile app supply chain. For example, i n a scenario w h e n the attacker modifies the code of an app and adds malicious code that spies on users or steals their data. This type of attack is difficult to detect, as the app may seem to be working correctly for a longer period of time. The Safety Widget can detect unauthorized code manipulation via the freeRASP callback, protecting the app from this threat. 3. M3: Insecure Authentication/Authorization The attacker may try to trigger privileged functionality v i a a user account w i t h low-privilege permissions, w h i c h may lead to data loss or unpermitted app modification. This threat presents a more severe problem i n case the authorization is performed on a device level only instead of using a remote server. Insufficient authentication may lead to the execution of the app's functionality anonymously. 4. M4: Insufficient Input/Output Validation If the data received by an app are not validated properly, the app may be vulnerable to typical attacks that focus on input data, 20 4- M O B I L E SECURITY including SQL injection and cross-site scripting [27]. Insufficient output validation may enable the attacker to modify the data and display incorrect output to users. 5. M 5 : Insecure C o m m u n i c a t i o n M o d e r n mobile applications often communicate w i t h remote servers, and this data transmission can be vulnerable to interception and tampering by attackers. The motives of these attackers may vary but are generally motivated by acquiring sensitive information, manipulating data, or engaging i n identity theft. 6. M 6 : Inadequate Privacy Controls Privacy controls are vital for safeguarding Personally Identifiable Information (PII), like names, addresses, and credit card details. A p p s managing PII can be vulnerable to data exposure due to insecure storage and communication, inadequate authentication and authorization, or insider attacks on the app's sandbox. To protect PII, data should be stored or transferred only w h e n necessary, and there should be secure access w i t h proper authentication for critical data. 7. M 7 : Insufficient Binary Protections The binary version of an app may contain valuable secrets like A P I keys or cryptographic information that can be further abused. In addition, some attackers may focus on identifying backend vulnerabilities using the app. Attackers can manipulate binaries to unlock premium features, bypass security checks, or introduce malicious code into the apps, distributing them through third-party stores or rebranding them. A l l apps are vulnerable to binary attacks, w i t h increased risk for those containing sensitive data or hardcoded algorithms, especially popular apps. Implementing safeguards like obfuscation and native code secrets can heighten security, though complete prevention is not guaranteed. 8. M 8 : Security Misconfiguration In mobile apps, this is caused by improperly configured security settings, permissions, or controls and potentially leads to 21 4- M O B I L E SECURITY vulnerabilities and unauthorized access. Attackers are looking for these misconfigurations for unauthorized data access or malicious actions. They can be individuals w i t h physical device access or malicious apps targeting vulnerabilities w i t h i n the app. Mobile apps are susceptible to security misconfigurations if they do not follow security best practices. Indications of vulnerability for misconfigurations include not reviewing default settings, weak access controls, and neglecting necessary security updates or patches for the app and its components. 9. M9: Insecure Data Storage Weak data storage i n mobile apps can be an easy target for various threat actors, including skilled adversaries, insiders w i t h malicious intent, state-sponsored actors, or cybercriminals. These individuals take advantage of vulnerabilities such as poor encryption, inadequate data protection, and weak management of user credentials. To reduce these risks, mobile app developers and organizations should adopt sufficient and u p to-date security measures, including robust encryption, secure data storage practices, and strict adherence to best practices i n mobile application security. 10. M10: Insufficient Cryptography Attackers targeting insecure cryptography i n mobile apps can break data confidentiality, integrity, and authenticity. Insecure cryptography i n mobile apps can prevail through weak encryption, short keys, poor key management, and poor implementation, all of w h i c h pose risks to sensitive data. To prevent these threats, developers should follow best practices, such as using secure cryptography algorithms like R S A , E C C , or A E S , securely storing these keys o n the device, and verifying the integrity and authenticity of the encryption process. 4.2 RASP Sometimes, it is not possible to control o n w h i c h devices a n app is installed. It may happen that the device is insecure and can be used 2 2 4- M O B I L E SECURITY as a tool to perform a sophisticated attack on the app. Therefore, to prevent these threats, controlling the app during its runtime is beneficial. This is where RASP can be helpful. R A S P stands for Runtime Application Self-Protection, and it is a technology designed to enhance the security of applications by actively monitoring and protecting them during their runtime. U n l i k e traditional security measures that focus on protecting the network and infrastructure, R A S P operates directly w i t h i n the application and so has access to the r u n n i n g software, p r o v i d i n g a layer of protection closely integrated w i t h the application [28]. The R A S P controls are a part of the application itself; therefore, no extra steps are required by users of the app, and if it does not detect anything, usually, it does not interfere w i t h the user interface i n any way [29]. A m o n g the key advantages of R A S P belong: • Real-time monitoring R A S P continuously monitors the application's behavior while it's running, allowing it to detect and respond to security threats as they occur. • Application-centric security R A S P focuses directly o n the application and understands its logic and context, making it effective at identifying and mitigating application-specific vulnerabilities and attacks. • Dynamic response W h e n R A S P identifies a potential security threat, it can take immediate action, such as blocking the malicious request, notifying the users, or terminating the app i n real time. It's important to note that R A S P is not a bulletproof solution, but rather a valuable layer i n the application's security. It makes it significantly harder to attack an application if it is protected by a R A S P solution compared to an app that doesn't use any extra protection. The potential attacker has to invest much more time i n reverse-engineering the app protected by R A S P [28]. 23 4- M O B I L E SECURITY 4.2.1 freeRASP ThefreeRASP, developed and maintained by Talsec, is a security library that provides a simple A P I that informs about detected threats, white it requires minimal code changes to the project. It includes a range of security checks, each specifically designed to safeguard against certain attack vectors. Therefore, the overall security of the application is improved. The library is built for A n d r o i d and iOS. However, a Flutterspecific plugin, f reerasp 5 , wraps these two implementations a n d exposes the original platform-specific A P I of the freeRASP directly to Flutter [30]. The checks provided by freeRASP are aimed at identifying potential threats to the application while it runs. Developers have then the flexibility to decide h o w they want to respond to the detected incidents. They can choose to have the application terminate itself, issue a warning to the user, retrieve detailed incident information, simply discard the threat altogether, or do any other action [31]. A s of version 6.3.0, w h i c h is the latest version at the time of writing the thesis, there are two ways h o w to receive information about detected threats. The preferred solution is to use the provided ThreatCallback class with parameters of type VoidCallback that are triggered when a threat is detected. A n instance of ThreatCallback is then attached as a listener to method a t t a c h L i s t e n e r , also provided by freeRASP plugin. Following is a n example implementation that prints the event to the console: // create the listener instance f i n a l c a l l b a c k = T h r e a t C a l l b a c k ( onAppIntegrity: () => print("App Integrity"), onObfuscationlssues: () => print("Obfuscation Issues"), onDebug: () => print("Debug"), onDeviceBinding: () => print("Device Binding"), onDevicelD: () => print("Device ID"), onHooks: () => print("Hooks"), onPasscode: () => print("Passcode"), onPrivilegedAccess: () => print("Privileged Access"), 5. https://pub.dev/packages/freerasp 2 4 4- M O B I L E SECURITY onSecureHardwareNotAvailable: () => print("Secure Hardware Not Available"), onSimulator: () => print("Simulator"), onUnofficialStore: () => print("Unofficial Store"), ); // attach listener and listen to threats T a l s e c . i n s t a n c e . a t t a c h L i s t e n e r ( c a l l b a c k ) ; The checks oifreeRASP include [32]: • Root or jailbreak detection When a device is described as "rooted" or "jailbroken," it means that the device's operating system has been modified to remove certain security restrictions imposed by the device manufacturer or operating system developer. These two terms are related to A n d r o i d and iOS operating systems, respectively. Both can be done for purposes that are not h a r m f u l to the user or other apps installed on the device, such as customizing the U I of the device. However, they also open the device to potential security vulnerabilities, as malicious software installed from untrusted installation sources, for example, can exploit the elevated privileges to compromise the device's security. In addition, according to local laws, rooting the device may void the warranty. In case of jailbreak, the warranty is always void. For this reason, some apps and services may check for rooted or jailbroken devices to determine if they are running on a device w i t h increased security risks. This is often done to prevent sensitive data leaks or functionality from being compromised. The threat is received via the onPrivilegedAccess callback. O n A n d r o i d devices, rooting is the process of obtaining root access or administrative privileges on the device. This allows users to access and modify the system files and settings that are typically restricted. O n iOS, jailbreaking is the process of removing the software limitations and restrictions imposed by Apple on iOS devices. This enables users to install applications from untrusted installation sources and make system-level changes that are not allowed on non-jailbroken devices. 25 4- M O B I L E SECURITY • Simulator detection This control is able to detect whether the app is running on an A n d r o i d emulator or iOS simulator. Such an environment can be exploited by attackers, w h o can trace program execution, inspect system states, reset to saved images, or monitor application behavior. While not all emulator or simulator usage implies a threat, there are certain types of applications that should keep confidential data hidden. Therefore, they should not permit simulators, such as banking apps, for example. The threat is received via the onSimulator callback. • Hooks detection Hooks can intercept and modify the system or application calls. This technique is called hooking, and in the hands of an attacker, it can lead to unauthorized access to sensitive client data, all without altering the source code. W h e n the function targeted by hooking is invoked, the hooking mechanism redirects the execution flow to another function, allowing for custom code to be executed before, after, or in place of the original function. The behavior of the intercepted function can be altered in many ways. These include the adjustment of input parameters, modification of the return value, or the execution of additional code that was not initially included within the function. Some of the popular h o o k i n g frameworks currently used include F r i d a 6 , X p o s e d 7 , and C y d i a Substrate8 . The threat is received via the onHooks callback. • App tampering detection This control refers to the unauthorized modification of a mobile application's code or data, often with the purpose of bypassing security measures or introducing malicious code. Attackers may reverse engineer the app, alter its codebase, manipulate data, or bypass security features. This poses threats to the app's integrity and user data. Other measures that can reduce the risk 6. https://frida.re/ 7. https: / /abhiappmobiledeveloper.medium.com/android-xposed-f ramework- ee763e5dda8e 8. http://www.cydiasubstrate.com/ 2 6 4- M O B I L E SECURITY of app tampering include code obfuscation, integrity checks, and encryption. The threat is received via the onAppIntegrity callback. • Debugger detection Besides the usual use-case, w h i c h is to follow the flow of the program during its execution, a debugger can also be attached to an application w i t h the goal of reverse engineering, checking memory values, and stealing confidential information. The library w i l l trigger a corresponding callback w h e n a debugger is attached. The threat is received via the onDebug callback. • Unofficial installation source detection Usually, the app is installed via official stores like Google Play or A p p Store. However, the app may be distributed through unofficial app stores or various online forums where pirated content is shared. These are often used to share modified versions of the app that, for example, unlock the p a i d features of an app for free. However, these may come with undisclosed and potentially h a r m f u l alterations. Permitting only official installation sources safeguards both the end-users and the application's owner. This callback is similarly triggered w h e n installing the application v i a alternative methods such as through a web browser, file manager, cloud storage, or Xcode build. The threat is received via the onUnof f i c i a l S t o r e callback. • Device b i n d i n g detection Device binding refers to the process of associating an instance of an application to a specific mobile device. This technique is used to identify instances of an application that has been moved to a different device. It does not, however, recognize a fresh installation of the application, for instance, when someone purchases a new device and transfers their apps to it. Closely related is also the devicelD check. It determines whether the device's unique identifier has been altered. Such an event may happen if the application is reinstalled, provided that no other applications from the same developer are installed on the device. 2 7 4- M O B I L E SECURITY The threat is received via the onDeviceBinding and onDevicelD callbacks. • Detection of m i s s i n g secure hardware A s smartphones are more often used for h a n d l i n g sensitive data, such as accessing banking information, it is becoming a standard for them to have a secure storage area for sensitive information, including cryptographic keys, passwords, certificates, a n d other credentials. Both i O S a n d A n d r o i d have their o w n solutions, the KeyStore for A n d r o i d and Keychain for iOS [33] [34]. Developers can use these to securely store user credentials, encryption keys, and other data. They both ensure that the information stored inside is protected f r o m unauthorized access and should be the default storage for secure data. The freeRASP checks if the cryptographic keys are stored inside secure hardware. The threat is received via the onSecureHardwareNotAvailable callback. • Passcode detection Setting u p a passcode provides a protective barrier for the i n tegrity of personal data stored inside smartphones, guarding against unauthorized access if the device is stolen, and helps to prevent from unauthorized use. The freeRASP detects if the device has any passcode set up and fires a callback otherwise. The threat is received via the onPasscode callback. • M i s s i n g obfuscation detection A p p code obfuscation is beneficial because it enhances the security of mobile applications by making it much more challenging for a n attacker to reverse engineer, tamper w i t h , or steal the source code. B y obfuscating the source code, the code logic is better h i d d e n from unauthorized access to sensitive information and intellectual property. W h e n the source code is not obfuscated properly enough, freeRASP will notify about it. This check is most useful during the development process to inform the developer that obfuscation should be activated. The check is available o n A n d r o i d only. The threat is received via the onObfuscationlssues callback. 2 8 5 Design choices This chapter explains the final architecture of the Safety Widget, i n cluding state management, localization, and themes, along w i t h other architectural alternatives considered prior to development. 5.1 Global state management Flutter itself only comes w i t h a basic mechanism for managing state w i t h i n the scope of a widget using the StatefulWidget and its setState method, w h i c h is c o m m o n l y used for managing local state changes w i t h i n a widget, and the InheritedWidget, w h i c h propagates the i n formation d o w n the widget tree [2]. However, although the global state could be managed through the InheritedWidget class, any change to the shared data w i l l trigger a rebuild of all the descendants that depend on that data. In large and complex widget trees, this can lead to unnecessary rebuilds and impact performance. Luckily, there are additional plugins that offer global state management functionality. The choice of state management solution then depends on various factors that are often different for each app, i n cluding the complexity of the app, maintainability of the solution, the team's familiarity w i t h different patterns, and also personal prefer- ences. The state management plugins considered are: • Provider This package is commonly used for managing state and sharing data between different widgets i n an app. It simplifies updating and passing data throughout the widget tree, reducing the need for more traditional state management methods. It utilizes the ChangeNotifier class to handle state changes and notify listeners w h e n data changes and a Consumer, w h i c h initiates rebuilding a part of the widget whenever there are changes i n the state being listened to. The rebuild only occurs w h e n it is necessary [35]. • BLoC (Business Logic Component) It is a state management architecture that enables better scala- 29 5. D E S I G N CHOICES bility and maintainability of Flutter applications. It separates the presentation layer from the business logic and data layer, promoting a clean and organized codebase. In this pattern, the application's state is managed by bloc components, w h i c h are responsible for handling data transformations, business logic, and communication w i t h external sources. In this pattern, the U I components dispatch events to the bloc components, emitting n e w states back to the U I . Flutter B L o C is implemented using streams and sinks to manage asynchronous data, making it most suitable for h a n d l i n g the state of complex apps. H o w ever, its complexity can introduce too m u c h overhead to apps w i t h thin business and data layers [36]. • Riverpod Designed to be a simple, intuitive, and flexible solution for managing application state. Riverpod package is based on the Provider package and introduces a more granular and declarative w a y of managing dependencies and states. One of Riverpod's key features is its emphasis on dependency injection, allowing easier testing. Riverpod also incorporates a provider and notifier that makes h a n d l i n g asynchronous operations easier and efficiently rebuilding U I components w h e n state changes [37]. • GetX A high-performance library providing a reactive architecture that minimizes boilerplate code. Its architecture enables the separation of view, presentation logic, business logic, dependency injection, and navigation, all without context, making it totally independent from the widget tree. Compared to other libraries, it has support for localization and theme management support out-of-the-box, which is a nice addition w h e n compared with other libraries. GetX uses a reactive p r o g r a m m i n g model, enabling efficient updates to the U I w h e n the underlying data changes. 30 5. D E S I G N CHOICES 5.1.1 C h o o s i n g the right framework Initially, it seemed as the best option to use the GetX package, mostly due to reduced boilerplate and independence from the app's context, which w o u l d make setting u p the Safety Widget easier. What's more, the out-of-the-box support for localization and switching themes w o u l d make the app's architecture m u c h easier. However, if GetX w o u l d be chosen, it w o u l d create an extra dependency for apps i n tegrating SafetyWidget, as GetX requires modification of the Materia l A p p 1 . It turns the widget into GetMaterialApp. Because the Safety Widget receives the MaterialApp widget from the integrating app, it w o u l d already have to be received with the GetX wrapper. Therefore, GetX was rejected, as the external dependency w o u l d create a pointless barrier for integrating apps. BLoC was also discarded. Although it allows for a nice decomposition of the app logic, i n the case of Safety Widget, it w o u l d introduce too m u c h boilerplate, as the data and presentation layers are not too complex for B L o C to be advantageous. In the case of Riverpod, it was too m u c h granularity that ruled out the package. If Riverpod was used, there w o u l d have to be a separate provider for each feature, w h i c h w o u l d make the state management unnecessarily complex. A l s o , the app w o u l d have to be w r a p p e d i n a generic Provider Scope, w h i c h w o u l d combine all SafetyWidget notifiers w i t h other eventual notifiers from other parts of the app. For the above reasons, the Provider package was chosen. Because of its simplicity and popularity, it is an ideal state management package for an app that has a m i n i m a l business layer, doesn't create any external dependencies, allows to combine multiple observable values into a single provider, and creates provider scope specifically for listed providers. 1. A fundamental widget in the Flutter framework that serves as the top-level container for a Material Design-themed Flutter application. 3 1 5.2 Starting the freerasp plugin 5. D E S I G N CHOICES To provide as secure solution as possible, the checks oi freerasp plugin must be executed immediately after the app is opened. This represents a significant obstacle for the whole design of the widget because additional plugins are usually executed only w h e n other widgets trigger them or are directly a part of the active widget tree. If the start of freerasp were bound to the Safety Widget icon, there would be a significant delay between the app start a n d completion oifreerasp checks that w o u l d enable to use the app i n scenarios where the device does not pass the security audit and app should not be permitted to open. Ideally, freerasp should be started inside the main() function of the Flutter app [38], just before the app itself is started b y the runAppO function. A s Safety Widget is just a Flutter package, it cannot access the mainO function directly a n d execute its o w n code there. Instead, it needs to postpone the execution of the runAppO u p to a point where it can start freerasp itself. This can be achieved b y passing the runApp () function or the root widget of the Flutter app as a property to an initializer class, w h i c h can start freerasp first, set u p all threat reactions a n d start the app after all that is completed. This procedure is shown i n the U M L Activity diagram i n Figure 5.1 As a result, the Safety Widget package w i l l consist of 2 parts: SafetyWidgetScope, a class responsible for setting up freerasp a n d its execution before r u n n i n g the integrating app. The class w i l l have an optional feature that w i l l await the completion of the freerasp security audit. In case this option is enabled, the SafetyWidgetScope w i l l either keep the app o n the original splash screen, or w i l l show an additional loading screen until the security audit is completed. O n l y after that w i l l the integrating app be started. 32 5. D E S I G N CHOICES iC User opens app J cCall SafetyWidgetScooe No ^ / 1CS o 1 Should await freerasp security audit? No \/ Yes -0Should display splash screen? Show splash screen MAwait 'awaitlnitialChecksDone' method I Show alertJj ^ Show a l e r t ^ • Received threat with kill reaction? Should show alert? ( Set up Safety Widget localization 3 ^ Set up Safety Widget theme ^ ^ ^ R e a c t to received threats^ ^ U s e r closes a p p ^ — C Close app Figure 5.1: Visualization of application start. 5.3 Customization A s per the requirements of the Safety Widget, the final product must be highly customizable. This means that the widget must be able to: • change the color and size of the Safety Widget icon, • change localization and a d d other translations, • change theming and add/modify available themes, • change the layout of the widget, • a d d additional reactions to the threats. 3 3 5. D E S I G N CHOICES Flutter supports localization using the flutterlocalization 2 and intl3 . Because flutter localization requires modification of the MaterialApp, it was discarded as it w o u l d create a dependency on a third-party library, w h i c h I wanted to avoid. In the case of intl, the p l u g i n could collide w i t h the rest of the application, if the app used a different locale than the Safety Widget. Therefore, I created a custom localization implementation for the Safety Widget. To support all the requirements of the package, the architecture of the Safety Widget must be built around them i n the first place. This, however, plays quite nicely w i t h the requirement to start freeerasp as soon as possible, because the customization can be resolved within the top-level SafetyWidgetScope class as well. The class w i l l have to receive the BuildContext of the Flutter app and be extended w i t h relevant properties. This w i l l be explained i n greater detail i n the following chapter. 5.4 Local storage A l t h o u g h the Safety Widget does not rely on any data from a- remote server and does not need to handle any user data, there is an optional feature to let the user change the theme and localization of the Safety Widget independently of the app's settings. Those changes must persist closing the app to provide consistent and predictable behavior. In Flutter, there are multiple ways to store the data persistently. Some solutions use S Q L databases, for example the sqflite 4 or drift 5 plugins. However, solutions based on S Q L are more suitable for larger applications that need to process more complex data. Therefore, i n the case of the Safety Widget where just a couple of setting has to be saved, they are not the ideal data storage option. The most suitable option is to save the settings into shared preferences, there are many plugins on pub.dev that provide access to the 2. https:/ /pub.dev/packages/flutter_localization 3. https://pub.dev/packages/intl 4. https://pub.dev/packages/sqflite 5. https://pub.dev/packages/drift 3 4 5. D E S I G N CHOICES local storage of the device, but two most popular are sharedpreferences 6 and flutter_secure_storage 7 . In the case oi flutter_secure_storage, the data are stored using Keychain on iOS, whereas a KeyStore-based solution is used o n A n d r o i d . The sharedpreferences p l u g i n uses NSUserDefaults o n iOS and macOS, SharedPreferences o n A n d r o i d . The data that the Safety Widget must store are not sensitive. They are settings of the app only (language, theme, show hints toggle). Therefore, it is sufficient to use the 5.2 sharedpreferences. This plugin is simple to use and does not a d d any extra complexity to the app caused b y the encryption of the stored data. SharedPreferences A storage Local Database prefs: SharedPreferences? (- getLocalizationQ: Future t- setLocalizationflocale: Locale): Future t- getDontShowAgainO: Future t- setdontShowAgain(newValue: bool): Future t- isDarkModeO: Future t- setTheme(isDarkMode: bool): Future I Locale countryCode: String? languageCode: String hashCode: int scriptcode: String? SettingsModel SafetyWidgetScope Figure 5.2: Local storage architecture. 6. https://pub.dev/packages/sharedpfe/erences 7. https: / /pub .dev /packages /flutters ecures torage 35 6 UX/UI This chapter introduces the provided design of the app along with its extensions and modifications. The Screenshots from the final version of the Safety Widget can be seen i n Attachment B. 6.1 Provided design The Safety Widget requirements specify that the widget should be based on the existing design of the CybeTribe app1 . However, the scope of the CybeTribe app is slightly different; it is aimed at creating community of people interested in mobile security, whereas Safety Widget has a broader audience, and is focused on a security of a particular device/application. Because of these deviations, it was not possible to base the whole design on the CybeTribe app. 6.1.1 Similarities w i t h the CybeTribe Both of the projects internally use the security audit provided by Talsec. Therefore, it is possible to share the most of security audit page. The only difference is that CybeTribe's security audit page also contains information about other apps installed on the device (App Intelligence tab), as s h o w n i n Figure 6.1. This is out of the scope of the Safety Widget, therefore, the tab was removed. 1. https://play.google.com/store/apps/details7i 36 6. U X / U I Security Audit O Device App App Intelligence Biometrics ^ / Face recognition and fingerprints make unlocking your device and payments easier Passcode Lock ^ A passcode protected device greatly improves your safety. Secure Enclave ^ / An isolated system for secure data storage is indispnsible against advanced attackers. Root ^ An isolated system for secure data storage is indispnsible against advanced attackers. Emulator ^ An isolated system for secure data storage is Ten Commandments Figure 6.1: Security A u d i t page i n CybeTribe serving as a starting point for the dark mode. A l s o , CybeTribe design contains a pleasant color palette, w h i c h was completely reused a n d slightly extended i n the Safety Widget. In addition, all icons a n d text fonts w i t h corresponding styles for particular elements were also taken from CybeTribe. 6.2 Design extension Unfortunately, the provided design does not cover the whole Safety Widget requirements. Because of that, I h a d to create an additional design for the missing parts of the Safety Widget. 6.2.1 Dark mode Most notably, CybeTribe does not support dark mode or have corresponding designs. Fortunately, the color palette is extensive, w h i c h 3 7 6. U X / U I made it possible to create the dark mode from that palette and base it on other pages that are i n CybeTribe and not i n the Safety Widget. For example, the recommendations i n the CybeTribe app imitate how the dark mode could look like, as s h o w n i n Figure 6.2.