Главная » Просмотр файлов » 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), страница 50

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

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

This is because the smallest unit of memoryisolation is the process and so you might have invited a wolf in sheep’sclothing into the fold!ExampleMost devices have a control panel through which various system settingscan be configured. For instance it might allow you to change the systemtime and date or set the Bluetooth device name.

Moreover, the set ofthings that can be configured vary from device to device. If there isn’tany support for Bluetooth then there’s no need to change the Bluetoothdevice name, etc. Symbian OS v8, before the advent of platform security,provided support for control panels through the classes CApaSystemControlList and CApaSystemControl which can be foundin epoc32\include\apgctl.h. In particular, these classes allowedthe UI layer to find and load at run time30 plug-in DLLs that providedindividual control panel items, such as the Bluetooth and Time dialogs.Anyone could provide their own control panel plug-in and so affect thedevice configuration.

Such a plug-in could easily be of poor quality andadversely affect the device by accidentally deleting all network accessprofiles, for instance.When platform security was introduced in Symbian OS v9, continuingto allow plug-ins to be provided as DLLs – effectively using Buckle (seepage 252) – was not acceptable. The key to understanding this is toconsider what capabilities you’d give to the process loading the controlpanel plug-ins. ReadDeviceData and WriteDeviceData are obviouschoices but LocalServices is also needed to change the Bluetoothsetting. Is there a GPS chip in the device? If so, the Location capabilitymight be needed.

The problem is that the Control Panel has such a diverseset of possible needs that its process would soon end up needing virtuallyall capabilities. This would not just present a valuable target for malicioussoftware to try to subvert but would also force providers of simple controlpanel dialogs to get their plug-ins signed with a number of restrictedsystem capabilities. They might not be able to justify the expense ofobtaining them when their software doesn’t require the capabilities toperform its functionality.Instead another way is needed to allow plug-ins to be loaded whilstbreaking the dependency of a plug-in’s capabilities on those provided bythe framework.30 Viaa mechanism conceptually similar to ECom though much simpler.262SECURITYSolutionThe solution presented here allows plug-ins to operate at a differentlevel of trust from the framework. This is achieved by implementing plug-ins as separate processes that are created on demand by theframework process which decouples the framework and the plug-ins toallow them to have completely different protected memory spaces andcapabilities.This is reflected in the name of the pattern because, between theframework and the plug-ins, there is a barrier that prevents infection,known as malicious attacks, from spreading in either direction.StructureThe framework creates plug-ins at run time by calling one of the RProcess::Create() APIs resulting in Figure 7.8.Framework ProcessPlug-in ProcessRuntime LinkFrameworkPlug-in0..*Figure 7.8Structure of the Quarantine patternNote that it is not enough for a plug-in to be in a separate thread.This is because a thread containing a plug-in in the same processas the framework would still be able to access the memory of theframework thread as well as having the same capabilities as the frameworkprocess.

The execution time overhead of crossing a process boundaryis always the same as or greater than that of simply crossing a threadboundary. For most current devices, the difference between the two isnot significant, compared to the total time taken,31 so this shouldn’t bea problem. In addition, the use of this pattern assumes that there isn’tany extensive communication between the framework and a plug-inanyway.Interestingly, this pattern can be seen as the inverse of the Secure Agent(see page 240) in that we are separating out the less trusted componentsinto their own processes.31 This is true for the multiple-memory model used on ARMv6 processors which arecurrently the most common CPUs on Symbian OS devices.

Unfortunately this isn’t true forolder devices using the moving-memory model on ARMv5 processors where the contextswitch between processes is 35 times slower than between threads in the same process (seeAppendix A for more details).QUARANTINE263DynamicsFigure 7.9 shows how a plug-in process can be loaded. It uses theRProcess::Rendezvous() synchronization technique to co-ordinatethe initialization of a plug-in process. This works in the same wayas thread synchronization does and is described in more detail in theSymbian Developer Library.Figure 7.9 Dynamics of the Quarantine patternAs you can see from the diagram, both the framework and a plug-inhave the opportunity to authenticate each other by performing securitychecks during the plug-in loading procedure.

These security checks arean essential part of mitigating the security risk that a process other thanthe framework may attempt to load a plug-in. To avoid this, a plug-inprocess must check that it hasn’t been invoked and passed informationby a process spoofing the framework. If the security checks fail, theplug-in process should end its initialization procedure prematurely. The264SECURITYframework however has an advantage, in that it is able to perform itssecurity check on a plug-in process before the plug-in has a chance toexecute any code.

This allows the framework to Kill() a plug-in if itfails the security checks.This solution only allows a limited amount of communication betweenthe framework and each plug-in once a plug-in has been created. This isbecause any communication channels needed have to be set up during theloading of each plug-in. Since you only need a fire-and-forget extensionpoint, as assumed in the context, this shouldn’t be an issue. If you doneed to maintain significant communication between the framework anda plug-in then you should consider using Cradle (see page 273) insteadof this pattern.ImplementationFrameworkBefore a plug-in can be loaded, you need to be able to list all the available plug-ins that implement the interface required by the framework.Since we’re not loading DLLs, ECom can’t be used – you need to provideyour own alternative mechanism.

One way would be to specify thatwhen a plug-in is installed a resource file should be placed in a standard location with a specific name, such as \resources\<frameworkname><framework UID3>\plugin<plug-in UID3>.rsc. Notethat the UID3 values are used to ensure that the directory and eachindividual plug-in RSC file are unique. A plug-in’s resource file needs tocontain at least the name of the EXE file that can be used to create theassociated plug-in process. You can then use the TFindFile class tosearch for it.The following is an illustration of how to implement the loading of aplug-in within framework.exe:_LIT(KPluginCommand, "<static plug-in initialization data>");// This function is passed in the plug-in to load which has been// identified elsewherevoid CFramework::LoadPluginL(const TDesC& aPluginName){RProcess plugin;User::LeaveIfError(plugin.Create(aPluginName, KPluginCommand));CleanupClosePushL(plugin);////////if(1) Security checks on the plug-in should be performed here usingthe RProcess functions Hascapability(), SecureId() and Vendorld().For example, the following code checks that the plug-inhas the ReadUserData capability:(!plugin.Hascapability(EcapabilityReadUserData,__PLATSEC_DIAGNOSTIC_STRING(QUARANTINE265"Checked by CFramework::LoadPluginL"))){User::Leave(KErrPermissionDenied);}// (2) Additional arguments can be passed to the plug-in process at// this point using the RProcess::SetParameter() functions.

For// example, you could pass over some dynamic data:TPckg<TDynamicPluginData> pckg(TDynamicPluginData(...));plugin.SetParameter(KProcessSlotDynamicPluginData, pckg);TRequestStatus stat;plugin.Rendezvous(stat); // Synchronize with the plug-in processif (stat != KRequestPending){plugin.Kill(0); // Abort loading the plug-inUser::Leave(stat.Int());}else{plugin.Resume(); // Logon OK – start the plug-in}User::WaitForRequest(stat); // Wait for start or death// We can’t use the "exit reason" if the plug-in panicked as this// is the panic "reason" and may be "0", which cannot be// distinguished from KErrNoneTInt ret = (plugin.ExitType() == EExitPanic) ? KErrGeneral : stat.Int();User::LeaveIfError(ret);CleanupStack::PopAndDestroy(); // plug-in}The security checks should be performed as specified at (1) in the abovecode.

The TCB is used to perform the security checks on your behalf,which guarantees that they cannot be tampered with. For instance, if theexecutable containing the plug-code is on removable media, the TCBchecks that it hasn’t been tampered with off the device.Note that the above allows for limited communication between theframework and a plug-in. At (2) the framework can pass information to aplug-in process via 16 possible environment slots.32 These can be set bythe framework to contain items such as file handles; handles to other system resources (such as global memory chunks, mutexes and semaphores);integers, descriptors, and TRequestStatus objects, amongst others.

Inreturn, a plug-in process can use these same mechanisms to pass information back to the framework so long as the framework is expecting thatthis might happen. One example of this would be:1. The framework passes a file handle to a plug-in on creation and callsRendezvous() to wait for the plug-in process to initialize itself.32Fewer than 16 are available if the plug-in is also an application since theapplication framework uses some for its own purposes. See CApaCommandLine::EnvironmentSlotForPublicUse().266SECURITY2.During the plug-in’s initialization, the plug-in writes data using thefile handle. When it is finished, it calls Rendezvous().3.When the framework process resumes, it assumes the plug-in hasfinished with the file handle and reads the new data that it points to.4.The data provided by the plug-in is validated before being used.For more information see the Symbian Developer Library.Plug-insWhen creating a plug-in, you first need to decide what capabilities toassign it.

This will depend entirely on what functionality you need itto perform and the cost of signing your plug-in. Once you’ve chosenthe capabilities, you need to assign them to your plug-in code via aCAPABILITY statement in the MMP file for your plug-in EXE. For moredetails of the MMP file syntax, see the Symbian Developer Library.The next step is to implement the process entry point as illustrated bythe following code snippet:Static void RunPluginL(){// (3) Security checks on the framework should be performed at this// point using the User functions CreatorHascapability(),// CreatorSecureId() and CreatorVendorId().

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

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

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

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