Главная » Просмотр файлов » Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356

Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879), страница 51

Файл №779879 Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (Symbian Books) 51 страницаIssott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879) страница 512018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 51)

For example, the// following code checks that the framework has the LocalServices// capability:if (!User::CreatorHascapability(ECapabilityLocalServices,__PLATSEC_DIAGNOSTIC_STRING("Checked by RunPluginL"))){User::Leave(KErrPermissionDenied);}// (4) Any arguments passed to the plug-in from the framework can// be accessed here using the User functions: CommandLineLength(),// CommandLine, ParameterLength() and the Get...Parameter() variants.// For example:TBuf<512> cmd;User::CommandLine(cmd);// Parse contents of cmd// Get additional arguments from the environment slotsTPckgBuf<TDynamicPluginData> dataPckg;User::LeaveIfError(User::GetDesParameter(KProcessSlotDynamicPluginData,dataPckg));TDynamicPluginData& data = dataPckg();// Initialization complete, now signal the framework// (5) Implement here any plug-in-specific functionality that the// framework expects to happen synchronously.RProcess::Rendezvous(KErrNone);QUARANTINE//////////}267(6) Implement here any plug-in-specific functionality that theframework expects to happen after the plug-in has finished loading.As much of the implementation should be executed here as possible tominimize the period during which the framework is blocked waiting forthe Rendezvous() above.// Entry point for the plug-in processTInt E32Main(){__UHEAP_MARK;CTrapCleanup* cleanup=CTtrapCleanup::New();TInt ret=KErrNoMemory;if (cleanup){TRAP(ret, RunPluginL());delete cleanup;}__UHEAP_MARKEND;return ret;}The security checks should be performed at (3) in the above codebefore any further action is taken since if the creating process isn’t trustedyou shouldn’t even look at the data passed across.

Even if the creatingprocess does pass the authentication checks, you should validate anyinput data before using it; this not only makes your plug-in more securebut also more reliable.ConsequencesPositives• This pattern allows the plug-ins to run under the capabilities oftheir own choosing, independent of what the framework specifies.This leads to both the framework and each plug-in running withthe minimum capabilities that they individually, and not collectively,need.

The main benefits of this are that:• the security risk to the device is reduced• it is easier for developers to provide a plug-in.• There is a reduced security risk to the framework since the plug-insrun in a separate memory space.• There is a reduced security risk to the plug-ins since they each run ina separate memory space from the framework and the other plug-ins.• The capabilities of the framework can be increased without impactingthe plug-ins, which makes maintenance easier.268SECURITYNegatives• An additional attack surface has been added, which increases thesecurity risk although this is mitigated by the lack of any ongoingcommunication between the framework and the plug-ins.• It only directly supports very simple, one-shot communication between the processes via parameters and return values during theloading of the plug-ins.• Memory usage is increased due to the addition of an extra process(a default minimum RAM cost of 21–34 KB33 ), though this may justbe a transitory increase if plug-ins are short lived.• The responsiveness of the framework is decreased since the creationof a whole new process for each plug-in means that loading a plugin takes approximately 10 milliseconds longer.33 Whether this issignificant depends on how frequently a plug-in is loaded.Example ResolvedWhen the Control Panel framework was upgraded in Symbian OS v9 toreflect the increased security concerns, it was decided to use this patternto provide the solution.

Since control panel plug-ins are responsible forinteracting with the user, rather than just changing the plug-ins to beseparate processes they were changed to be separate applications. InSymbian OS v9, this meant they’d be separate processes too.In this example, the framework process is the TechView34 UI layerprocess shell.exe which provides the main screen after the device hasbooted. This runs with the PowerMgmt, ReadDeviceData, WriteDeviceData, DiskAdmin, SwEvent, ReadUserData and WriteUserData capabilities because it provides the main GUI to the user.

Thisprocess uses an updated version of the CApaSystemControlListclass to identify applications that have registered themselves as providingcontrol panel functionality by marking themselves with TApaAppcapability::EControlPanelItem:void CApaSystemControlList::UpdateL(){RApaLsSession appArcSession;User::LeaveIfError(appArcSession.Connect());CleanupClosePushL(appArcSession);User::LeaveIfError(appArcSession.GetFilteredApps(TApaAppcapability::EControlPanelItem,TApaAppcapability::EControlPanelItem));33 See34 TheAppendix A for more details.Symbian reference device UI.QUARANTINE269TApaAppInfo aInfo;// Fetch the control panel information one by one and add a// corresponding control to the control listwhile(appArcSession.GetNextApp(aInfo) == KErrNone){// Update list}}The above code means that when a new control panel application isinstalled a new icon appears in the Control Panel, as shown in Figure 7.10.(a)Figure 7.10(b)Control-panel application icons in a) S60 and b) UIQApplications that have been identified as providing Control Panelfunctionality are modeled in the framework process by an updatedversion of the CApaSystemControl class.

When a Control Panel iconis clicked, the following code is executed:void CApaSystemControl::CreateL(){RApaLsSession appArcSession;User::LeaveIfError(appArcSession.Connect());CleanupClosePushL(appArcSession);TThreadId threadId;CApaCommandLine* commandLine = CApaCommandLine::NewLC();commandLine->SetExecutableNameL(iFullPath);270SECURITYcommandLine->SetCommandL(EApaCommandRunWithoutViews);User::LeaveIfError(appArcSession.StartApp(*commandLine, threadId));CleanupStack::PopAndDestroy(2, &appArcSession);// Log on to the newly started control panel thread and wait// till it exitsRThread thread;User::LeaveIfError(thread.Open(threadId, EOwnerThread));TRequestStatus status;thread.Logon(status);User::WaitForRequest(status);thread.Close();}The above code results in a separate application being created that isdisplayed at the forefront of the screen.

The framework synchronouslywaits until the user has dismissed it before continuing and hence hasno need to Rendezvous() with a plug-in process as described in thepattern solution above.Note that no security checks are applied to a plug-in process. Theframework relies on the platform security architecture to prevent theplug-in from doing anything it doesn’t have the capabilities for. Theworst thing that can happen is that the user is confused by a plug-in’sdialog boxes in some way and won’t run it again.

Since these thingsonly happen when the user clicks on a particular control panel icon whywould any ‘malicious’ code bother? The Control Panel doesn’t need totrust its plug-ins; they just have to be trusted by the operating systemitself.One of the Control Panel plug-ins is the Bluetooth settings dialogwhich has responsibility for gathering Bluetooth configuration settingsfrom the end user as well as calling the relevant APIs to pass on thisinformation to the Bluetooth subsystem (see Figure 7.11).This Bluetooth control panel plug-in application is run with theNetworkServices, LocalServices, WriteDeviceData and NetworkControl capabilities. Note that this means it could not be loadedas a DLL into the framework process since it doesn’t have the PowerMgmtcapability. Even if it did have sufficient capabilities to be loaded as a DLL,it wouldn’t be able to perform its functionality at run time because theframework process doesn’t have the LocalServices capability.

Henceboth the framework and this plug-in are trusted to perform actions theother is not trusted to do.This plug-in chooses not to authenticate the process starting it sinceexecuting the process does not affect any security asset, such as whetherBluetooth is enabled or not, without the end user giving confirmationby clicking the Change or Edit button shown in Figure 7.11. Security isstill maintained because only the end user can affect the security assetsthrough the plug-in.

The worst that could happen if the plug-in was usedby a malicious application is that it could be repeatedly started and soQUARANTINE(a)271(b)Figure 7.11 Bluetooth settings dialog on a) S60 and b) UIQannoy the end user because the screen would keep showing the Bluetoothconfiguration dialog. This problem isn’t specific to Control Panel plugins and could happen to any application. The solution under platformsecurity, in both cases, is for Symbian Signed to prevent such maliciouscode from being signed and to revoke any signed applications that aresubsequently found to act in such a manner.

Unsigned applications canbe installed on Symbian OS devices but the end user is warned that whatthey’re doing could be unsafe.Other Known Uses• Messaging InitializationAnother use of the pattern can be found in the Symbian messagingarchitecture. A default message store35 is created if the message serverfinds either no message store or a corrupt message store when itstarts. As the final step, the messaging server then checks whether anexecutable mailinit.exe is present on the device. If it is present,the server starts this plug-in executable to allow customization ofthe mail store.

The behavior of mailinit.exe is defined by theUI family of the device. The typical behavior is to perform specificinitializations for each message type. For example, the SMS plug-intypically creates a default service entry.From a security viewpoint, the interesting thing about mailinit.exe is that the messaging server doesn’t have to worry about whether35 Withjust a root entry and any standard folders defined in the resource file msgs.rsc.272SECURITYor not it can trust it, because no information or requests are passed tothe plug-in.

Any customization of the messaging store performed bymailinit.exe has to be done by the plug-in process itself openinga session with the messaging server, and whether its actions are validis determined solely by its own capabilities, not by anything that itsparent does.Variants and Extensions• Combined Buckle and QuarantineIn this variant, a framework chooses to load plug-ins either via Buckle(see page 252) or via Quarantine (see page 260). This means that theframework loads plug-ins as DLLs into the framework process whena plug-in’s capabilities are compatible with those of the framework.Plug-ins are only provided as EXEs when the capabilities betweenthem and the framework process are incompatible.

This means theoverhead of creating a new process for a plug-in is avoided unlessabsolutely necessary.References• Buckle (see page 252) is an alternative way of providing an extensionpoint that is a simpler but less flexible solution to this problem.• Cradle (see page 273) extends this pattern to support an ongoingcommunication session between the framework and its plug-ins.• Chapter 3 contains patterns describing how you can improve execution performance or RAM usage by changing the point at which youload and unload plug-ins.• See the following document for more information on resource files:Symbian Developer Library Symbian OS guide System Libraries Using BAFL Resource Files.CRADLE273CradleIntentHost DLL plug-ins in separate processes, operating at different levels oftrust to your own, to securely increase the flexibility of your architecturewhilst maintaining communication with each plug-in.AKANone knownProblemContextYou need to provide a secure extension point in your component thatsupports extensive communication between the framework and the plugins whilst not overly restricting the plug-in providers.Summary• Architectural extensibility has to be provided.• The potential damage caused by plug-ins needs to be limited by minimizing the capabilities they execute with (principle of least privilege).• It’s desirable that the restrictions on who can provide plug-ins are aslight as possible.• You wish to allow plug-ins to operate with a different set of capabilitiesthan the framework.• You need to support a full communication channel between theframework and the plug-ins after the plug-ins have been loaded.DescriptionIf you’re reading this pattern then you’ve probably tried to get Buckle(see page 252) to work but found that it doesn’t provide a solution to thisproblem since you need to allow the plug-ins to operate at a differentlevel of trust to the framework.Quarantine (see page 260) is an alternative that does allow plug-ins tooperate at a different level of trust to the framework but it only directlysupports very simple, one-shot communication between the frameworkand each plug-in; in this context, we need to support a full communicationchannel between them.

Характеристики

Тип файла
PDF-файл
Размер
2,96 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6294
Авторов
на СтудИзбе
314
Средний доход
с одного платного файла
Обучение Подробнее