How to Clear DTC's internally? - autosar

I am trying to delete diagnostic information but I am strugling to find the configuration in Tresos which would enable ClearDTC interface.
What would be the right way to clear all DTC's internally from the context of SWC?

AUTOSAR Dem component has a standardized Client/Server Interface "ClearDTC", which has two operations:
ClearDTC
SelectDTC
In your authoring tool (not Tresos), you have to add these to your project with your SWC. (They can be found also in the AUTOSAR Blueprints)
You add a new R-Port (e.g. rDemClearDTC) with that PortInterface. In your runnable entity, you should add then for both operations of that interface a SynchronousServerCallPoint.
Finally, in your implementation you should then call these operations over the port by Rte calls.
void MySwc_Runnable(void) {
Std_ReturnType ret;
// sscp_SelectDTC
ret = Rte_Call_rDemClearDTC_SelectDTC(0xFFFFFFu, DEM_DTC_FORMAT_UDS, DEM_DTC_ORIGIN_PRIMARY_MEMORY);
// sscp_ClearDTC
ret = Rte_Call_rDemClearDTC_ClearDTC();
}
You might have to configure also in Dem a second DemClient, because this ClientId should be part of the Tresos-generated Dem ServiceSwComponent as port-defined argument.
The C/S Interface ClearDTC is (according to the Dem SWS) actually only related to ComplexDrivers and not normal ApplicationSwComponents. The question is also, why you would want to call ClearDTC at all from your SWC.

Related

How to Self-Lock a Javacard Applet

My question is whether it is possible to lock an applet from within the code of the applet itself as a countermeasure to detected manipulations from within the code.
The obvious choice is to use GPSystem.lockCard(); and it works, however I wonder if it is possible to only lock the applet. Also I can lock the applet itself from an authenticated session of the associated security domain. But is it possible from the applet code itself. It seems, given the GPSystem.setCardContentState(); method used with GPSystem.APPLICATION_LOCKED, so I also tested that but it does not work.
Rereading the description of the GP Card specification 2.2 PDF:
The OPEN shall reject any transition request from the Life Cycle State LOCKED;
In my Eclipse, the JavaDoc says:
The OPEN shall reject any transition request to the Life Cycle State LOCKED
What's going on here?
It's interesting to see how this mechanism evolved from GlobalPlatform Card specification 2.1.1 to 2.2.1 (still the same in 2.3):
In GP 2.1.1, only the card issuer (off-card entity) or the OPEN (as a result of "exceptions") is allowed to initiate locking of an application:
The Card Issuer has a mechanism to disable the continued execution status of an on-card Application. This mechanism may be invoked from within the OPEN based on exceptions handled by the OPEN or from the use of externally invoked commands. The Card Issuer is the only entity that may initiate the locking of an Application.
The method GPSystem.setCardContentState() is clearly defined to allow only state changes to application specific life-cycle states (values between 0x07 and 0x7F with the lowest 3 bits set). Since the constant for APPLICATION_LOCKED in later specifications is 0x80 setting this state is not allowed. This is also made clear in the notes to this method:
The OPEN shall reject any transition request to the Life Cycle States INSTALLED or LOCKED.
Consequently, trying to set the application state to locked from within the application itself must fail on a card implementing GP 2.1.1.
UPDATE (2016-05-20): I tested this on a few NXP JCOP cards (that are claimed to comply to GP 2.1.1) and setting values that have the upper bit set or any of the lower 3 bits cleared indeed fails.
This changed in GP 2.2. Now, an application is allowed to lock itself:
The card has a mechanism to disable and subsequently re-enable the continued execution status of an on-card
Application. This mechanism may be invoked from within the OPEN based on exceptions handled by the OPEN or
from the use of externally invoked commands. An Application with Global Lock privilege, the Application itself or
a directly or indirectly associated Security Domain are the only entities that may initiate the locking of an
Application.
The GP Card specification does not require an application to hold any specific permission to lock itself.
Unfortunately, the API specification for the method GPSystem.setCardContentState() is still not quite clear. First, the description of the method still states that only values between 0x07 and 0x7F with the lowest 3 bits set must be allowed:
This method sets the Application specific Life Cycle State of the current applet context. Application specific Life Cycle States range from 0x07 to 0x7F as long as the 3 low order bits are set.
Second, there are deviating notes in the API documentation thats part of appendix A of the GP Card specification 2.2 document and the JavaDoc in the API export files. While the notes in the specification were changed to:
The OPEN shall reject any transition request to the Life Cycle State INSTALLED;
The OPEN shall reject any transition request from the Life Cycle State LOCKED;
The notes in the API export files (GPSystem.java and JavaDoc) remained the same as in GP 2.1.1.
Consequently, if this method was implemented according to the specification, it should still reject setting the application life-cycle state to APPLICATION_LOCKED.
UPDATE (2016-05-20): I tested this on a NXP J3D081 (JCOP v2.4.2 R2) card (that is claimed to comply to GP 2.2). Setting values that have the upper bit set or any of the lower 3 bits cleared, unfortunately, fails.
However, there is also the method GPRegistryEntry.setState(). The documentation of this method states that:
A transition request to Life Cycle state other than APPLICATION_LOCKED and APPLICATION_UNLOCKED shall be accepted only if the invoking Application corresponds to this GPRegistryEntry;
An Application shall be able to lock and shall not be able to unlock itself;
Thus, it would be interesting to see if the following worked on the same card where using setCardContentState() failed:
GPSystem.getRegistryEntry(null).setState(GPSystem.APPLICATION_LOCKED);
UPDATE (2016-05-20): I tested this on a NXP J3D081 (JCOP v2.4.2 R2) card (that is claimed to comply to GP 2.2). Unfortunately, this fails as well. Btw. it does not seem to make a difference if null or JCSystem.getAID() is used as parameter for getRegistryEntry().
UPDATE (2016-06-14): According to Paul Bastian, an NXP representative has confirmed that applications cannot set themselves to locked state on JCOP v2.4.x cards.
UPDATE (2016-06-06): I tested this on a Infineon SLE97CNFX card (that is claimed to comply to GP 2.2.1) and it worked. I could successfully set the state to locked by using APPLICATION_LOCKED (0x80). The state is then set to previous_state | 0x80. Trying to set other state values that have the upper bit set (e.g. 0x8F) does not work (just as I expected).
In GP 2.2.1, the documentation of the method GPSystem.setCardContentState() was changed (again). The change note clearly indicates that the method was updated to now allow an application to lock itself (export file version 1.5. maps to GP 2.2.1):
export file version 1.5: this method now allows the application associated with the current applet context to lock itself.
The method definition was changed to:
This method allows the application associated with the current applet context to change its state to an application specific life cycle state or to lock itself. An application cannot unlock itself using this method.
The value range for the state parameter passed to the method now explicitly includes the value of APPLICATION_LOCKED:
bState - an application specific life cycle state (0x07 to 0x7F with 3 low order bits set), or APPLICATION_LOCKED (0x80).
Consequently, cards implementing GP 2.2.1 or higher should eventually allow applications to change their own life-cycle state to locked using the method GPSystem.setCardContentState().
UPDATE (2016-06-06): I tested this on a Infineon SLE97CNFX card (that is claimed to comply to GP 2.2.1 (or is it 2.3?)) and it worked. I could successfully set the state to locked by using APPLICATION_LOCKED (0x80). The state is then set to previous_state | 0x80. Trying to set other state values that have the upper bit set (e.g. 0x8F) does not work (just as I expected).
An alternative solution
What you could do to overcome your problem without being able to set the application life-cycle to state APPLICATION_LOCKED, is to use application-specific life-cycle states:
public class LockableApplet extends Applet {
[... applet installation / instantiation code ...]
private static final byte APPLICATION_STATE_UNLOCKED = (byte)0x07;
private static final byte APPLICATION_STATE_LOCKED = (byte)0x7F;
public boolean select() {
if (GPSystem.getCardContentState() == APPLICATION_STATE_LOCKED) {
return false;
}
return true;
}
public void process(APDU apdu) {
if (selectingApplet()) {
return;
}
if (GPSystem.getCardContentState() == APPLICATION_STATE_LOCKED) {
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
}
[... applet logic code ...]
}
}
Upon detecting a problem that should cause your application to be locked, you could lock the applet with the following call:
GPSystem.setCardContentState(APPLICATION_STATE_LOCKED);
You could later unlock the application again using a SET STATUS command through the security domain.
(Buyer beware: It seems this way simply does not work -- see comments)
(In context of GlobalPlatform Card Specification 2.2.1)
You must obey the Application Life Cycle State rules depicted in figure 5-2 (the arrow marked '5' applies here).
The correct way should be:
GPSystem.setCardContentState((byte)(GPSystem.getCardContentState() | GPSystem.APPLICATION_LOCKED));
or
GPSystem.getRegistryEntry(JCSystem.getAID()).setState((byte)(GPSystem.getCardCo‌​ntentState() | GPSystem.APPLICATION_LOCKED))
The 0x80 life cycle state is invalid for an application. See table 11-4 ( at least the b1 and b2 bits must be set, the b3 bit probably as well).
EDIT>
(I confess to write this answer based solely on the remembrance of fact that OPEN keeps the original state from which the entity was locked)
I am quite curious about this so I did some tests using the following applet (excerpt):
public void process(APDU apdu) {
byte[] buffer = apdu.getBuffer();
if(selectingApplet()) {
return;
}
short claIns = Util.getShort(buffer, ISO7816.OFFSET_CLA);
switch(claIns) {
case (short) 0x8007:
buffer[0]=GPSystem.getCardContentState();
if(buffer[0]==buffer[ISO7816.OFFSET_P1]) {
if(GPSystem.setCardContentState(buffer[ISO7816.OFFSET_P2])) {
buffer[1]=0x01;
} else {
buffer[1]=0x00;
}
} else {
buffer[1]=(byte)0xFF;
}
buffer[2]=GPSystem.getCardContentState();
apdu.setOutgoingAndSend((short)0, (short)3);
return;
default: {
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
return;
}
}
}
And the following APDUs:
8007070F03 // To test transition into Application Specific State
80070F8F03 // To test my theory
80070F8003 // To test the GPSystem.APPLICATION_LOCKED constant directly
The results for my set of cards (Gemalto, Morpho, JCOP -- unfortunately all of them are GP 2.1.1) are in line with Michael Roland's great answer and GP specs -- the application's attempt to block itself is refused.
Received response APDUs for all GP 2.1.1 cards:
8007070F03 -> 07010F9000 // Succeeded in transition from `07` to `0F`
80070F8F03 -> 0F000F9000 // Failed transition from `0F` to `8F`
80070F8003 -> 0F000F9000 // Failed transition from `0F` to `80`
Just a note: This tool is quite useful to determine the implemented GP version as it parses the Card Recognition Data.
Yes. It is common and intended operation of a GlobalPlatform application. You must install your application with the right privilege (gp -install -privs CardLock) and the code to do it is:
GPSystem.setCardContentState(GPSystem.APPLICATION_LOCKED);
You can later unlock the application with
gp -unlock-applet <aid>
There is no compliance to GP core spec per se. A product is GP compliant to a GP configuration. GP configuration are not free of charge. JCOP 2.4.x products are compliant to GP 2.2.x 'Mapping Guidelines of Existing GP 2.1.1 Implementation on v2.2.1' configuration. As the name suggests, this configuration is for backward compatibility mapping. Basically JCOP 2.4.x products are GP 2.1.1 compliant products only (with a couple features from GP 2.2.x). Global Lock privilege is optional for applets.
Yes, it is quite simple: use a private static boolean flag and check it in the beginning of the process(APDU apdu) method:
public class MiniApplet extends Applet {
public static void install(byte[] bArray, short bOffset, byte bLength) {
new MiniApplet();
}
protected MiniApplet() {
register();
}
private static final short SW_APPLET_IS_LOCKED = (short) 0x9199; //any error SW
private static boolean appletLocked = false; //static -> faster access, this flag is checked each call! "private" modifier is VERY important!
public void process(APDU apdu) {
if (selectingApplet()) {
return; //it is a good practice not to throw any exceptions on SELECT command
}
if (appletLocked) {
ISOException.throwIt(SW_APPLET_IS_LOCKED);
}
if (attackDetected()) { //implement your attack detection
appletLocked = true;
}
}
}

Windsor Castle Equivalent of Autofac's IStartable

I'd like to be able to implement this in my windsor castle container set up:
"For all types that implement IStartable in the current assembly register them and run the Start method for them."
Similar to what you can do using Autofac for things like registering Automapper mappings. eg
public class MyBlahViewModelMapper : IStartable
{
public void Start()
{
Mapper.CreateMap<MyBlahEntity, MyBlahViewModel>();
}
}
Autofac does it automagically.... I'm thinking Windsor can't help me here?
Windsor has its own IStartable interface. If you want Windsor to register your objects and create/run them immediately after that you'd use Startable Facility for that.
To clarify, there are two concepts here:
IStartable interface, which provides Start and Stop methods. This is a lifecycle interfaces that provide lifecycle callbacks: Start being called right after a component instance gets created (after the constructor runs)
Startable Facility, which forces your IStartable components to be instantiated and started immediately after installers have ran.
Here's what the code would look like:
container.AddFacility<StartableFacility>(f => f.DeferredStart());
container.Install(FromAssembly.This());
// by here all startable are started
If you're on Windsor 3.3 or later you can also manually trigger the startables to start (which is useful if you need to do some extra setup for them)
var flag = new StartFlag();
container.AddFacility<StartableFacility>(f => f.DeferredStart(flag));
container.Install(FromAssembly.This());
// do whatever else set up your app needs
// when ready, signal the flag
flag.Signal();
// by here all startable are started
The closest is Castle Windows Installers - they can trivially scanned from an assembly and installed (or 'started'). Installers are usually used to register components, but they can be used for other initialization as well.
Windsor uses installers (that is types implementing IWindsorInstaller interface) to encapsulate and partition your registration logic .. FromAssembly [makes] working with installers a breeze.
After creating an installer use one of the fluent configurations in the main IoC bootstrap, eg:
container.Install(
FromAssembly.This());
Note that the order is unspecified; installers that must occur in an order must be specified with an explicit order to Install, possibly through a modified assembly reflector.

U2 Toolkit for .NET - UniSession vs U2Connection

I'm struggling a bit with some of the base concepts of U2 Toolkit (and I've been quite successful with the previous version!).
First, I had to add using U2.Data.Client.UO; in order to reference UniSession or UniFile. This may just be general ignorance, but doesn't 'using U2.Data.Client' imply that I also want the .UO stuff under it?!?
Second - what (conceptually) are the differences between connecting via U2Connection's Open(), or UniSession's OpenSession()? Do each of them provide a different context in which to work?
Finally - while the examples provided in the doc and in Rajan's various articles are helpful, I'd like something a little more practical: how about a simple "here's how you read and write specific records in a Unidata file"?
Thanks!
Please see answer for the first and second questions
Regarding Namespace
If you want to develop application using ADO.NET ( SQL Access, UCI SERVER), you need one namespace (U2.Data.Client )
If you want to develop application using UO.NET ( Native Access, UO SERVER), you need two namespaces (U2.Data.Client and U2.Data.Client.UO)
U2.Data.Client namespace generally have Microsoft ADO.NET Specification Classes.
U2.Data.Client.UO namespace generally have UniObjects Native Specification Classes. As you have used in the past UODOTNET.DLL, you can feel all the Classes are there.
Regarding U2Connection/UniSession
This is by Design.
U2Connection.Open() calls UniSession.Open() when you use Accessmode=’Native’ in Connection String. You can verify from the LOG/TRACE File. In this case, basically, U2Connection and U2Session are same. U2Connection Class just passes connection string to UniSession Class and then UniSession Class uses this connection string and calls Open(). This is an improvement from the old way where you have used Static Class UniObjects(…) and there was no concept of standard connection string. Basically we replace Static Class UniObjects(…) to U2Connection Class and provided connection string capabilities.
U2Connection.Open() calls UCINET.Open() when you use Accessmode=’SQL’ in Connection String. You can verify from the LOG/TRACE File.
Is this clear()?

solving multiple inheritance (for precooked classes)

What I need: a class with two parents, which are ContextBoundObject and another class.
Why: I need to access the ContextBoundOject to log the method calls.
Composition works? As of now, no (types are not recognized, among other things).
Are other ways to do this? Yes, but not so automatable and without third-party components (maybe a T4 could do, but I'm no expert).
A more detailed explanation.
I need to extend System classes (some of which have already MarshalByRefObject (which is the parent of ContextBoundObject) for parent, for example ServiceBase and FileSystemWatcher, and some not, for example Exception and Timer) to access some inner workings of the framework, so I can log method calls (for now; in future it may change).
If I use this way I only have to add a class name to the object I want to log, instead of adding the logging calls to every method, but obviously I can't do this:
public class MyService:ServiceBase,ContextBoundObject,IDisposable{
public MyService(){}
public Dispose(){}
}
so one could try the usual solution, interfaces, but then if I call Run as in:
ServiceBase.Run(new MyService());
using a hypotethical interface IServiceBase it wouldn't work, because the type ServiceBase is not castable to IServiceBase -- it doesn't inherit from any interface. The problem is even worse with exceptions: throw only accepts a type descending from Exception.
The reverse, producing a IContextBoundObject interface, doesn't seem to work either: the logging mechanism doesn't work by methods, so I don't need to implement any, just an attribute and some small internal classes (and inheriting from ContextBoundObject, not even from MarshalByRefObject, which the metadata present as practically the same).
From what I see, extending from ContextBoundObject puts the extended class in a Proxy (probably because in this way the method calls use SyncProcessMessage(IMessage) and so can be intercepted and logged), maybe there's a way to do it without inheritance, or maybe there could be pre or post compiling techniques available for surrounding methods with logging calls (like T4 Text Templates), I don't know.
If someone wants to give this a look, I used a customized version of MSTestExtentions in my program to do the logging (of the method calls).
Any ideas are appreciated. There could be the need for more explanations, just ask.
Logging method calls is usually done using attributes to annotate classes or methods for which you want to have logging enabled. This is called Aspect Oriented Programming.
For this to work, you need a software that understands those attributes and post-processes your assembly by adding the necessary code to the methods / classes that have been annotated.
For C# there exists PostSharp. See here for an introduction.
Experimenting with proxies I found a way that apparently logs explicit calls.
Essentially I create a RealProxy like in example in the msdn, then obtain the TransparentProxy and use that as the normal object.
The logging is done in the Invoke method overridden in the customized RealProxy class.
static void Main(){
...
var ServiceClassProxy=new ServiceRealProxy(typeof(AServiceBaseClass),new object[]{/*args*/});
aServiceInstance=(AServiceBaseClass)ServiceClassProxy.GetTransparentProxy();
ServiceBase.Run(aServiceInstance);
...
}
In the proxy class the Invoke will be done like this:
class ServiceRealProxy:RealProxy{
...
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure)]
public override IMessage Invoke(IMessage myIMessage){
// remember to set the "__Uri" property you get in the constructor
...
/* logging before */
myReturnMessage = ChannelServices.SyncDispatchMessage(myIMessage);
/* logging after */
...
return myReturnMessage;
// it could be useful making a switch for all the derived types from IMessage; I see 18 of them, from
// System.Runtime.Remoting.Messaging.ConstructionCall
// ... to
// System.Runtime.Remoting.Messaging.TransitionCall
}
...
}
I have still to investigate extensively, but the logging happened. This isn't an answer to my original problem because I have still to test this on classes that don't inherit from MarshalByRefObject.

Separating Logic/GUI and user interaction

imagine you have a function that creates/copies/moves files. [logic]
For the case that a file that should be copied/created already exists you would like to ask the user to overwrite the file or not.[(G)UI]
What is your approach to implement this if (G)UI and logic are completely separated?
The first thing that comes into my mind would be the MVC-pattern, but this means that I would have to use it whereever I need user interaction.
Any other suggestions?
BTW: How would you implement this in non-OO-languages?
If GUI and logic are really separated, then this question should never arise. The program should, by design, either overwrite or not overwrite based on an option which has a default value. If the GUI is available, the option can be set.
In fact, although the obvious approach is to just have at it and begin copying, you could make a first pass looking for conflicts, and checking that the target device has enough free storage. Then, if there is a problem, terminate by doing nothing, unless there is a GUI in which case you can report the problem and ask whether to proceed anyway.
If you want to have a design in which the GUI can be invoked on a file by file basis, then design the logic around that as a set of n processes each of which copies one file, and has an optional GUI available in the error reporting section. The GUI can then reinvoke the copy-one-file logic.
I can see two ways:
You have two functions, file_exists(...) and copy_file(...). The UI side always calls file_exists first and asks the user whether to copy the file is it already exists.
You have only one function copy_file(bool force, ...), that by default fails if the file exists. So UI side calls the default version of the function, check if it failed and why, if it was because the file already exists, ask the user and try again with force=true.
In a Non OO language I would implement some kind of event queue where the parent (or child, depending on your design) UI polled for events while a 'busy' flag was true. Such an event lets the other side do other work while waiting for a 'they answered' flag to come true. Of course, some timeout in both directions would have to be observed as well as mutual exclusion. Basically, imply the principles of non-blocking I/O or your favorite theory on practical lock free programming here.
There are degrees of separation .. processes can communicate. Depending on your language of choice, you have shared memory segments, semaphores .. or IPC via relational DB with primitive signals. Its hard to be more specific with such a generic question.
See my comment, a little more information is needed so an answer can be crafted that works within your language of choice.
The first thing that comes into my mind would be the MVC-pattern, but this means that I would have to use it wherever I need user interaction.
And this is a bad thing why? Separating GUI and logic is exactly what the MVC pattern is for. Don't be scared of it just because it a has a long name -- as soon as you've separated GUI and logic you have a "view" and a "controller", at least, if not a "model" -- and if your application has state, you've got a model too. You just may not have admitted it to yourself yet.
From what I can see, there are really two problems:
We have an algorithm (logic) in which we would like to defer some operations and decisions to something else (e.g. user via UI).
We would like to avoid tight coupling between the algorithm and that something else.
If we use OO languages, there are several design patters which address these two specific problems.
Template Method pattern can solve #1. It does not solve #2 very well because the typical implementation is via inheritence.
Observer pattern looks promising too.
So really it is choosing and mixing the simplest one for the needs and most suitable for the language.
In practical terms, if talk about C# for example, we can implement Template Method and Observer hybrid like this:
// This will handle extensions to the FileCopy algorithm
abstract class FileCopyExtention
{
public abstract Response WhatToDoWhenFileExists();
}
// the copy function, pure logic
public static void Copy(string source, string destination, FileCopyExtention extension)
{
if (File.Exists(destination))
{
var response = _extension.WhatToDoWhenFileExists();
if (response == overwrite)
// overwrite the file
else
// error
}
}
// This is our user-interactive UI extension
class FileCopyUI : FileCopyExtention
{
public override Response WhatToDoWhenFileExists()
{
// show some UI, return user's response to the caller
}
}
// the program itself
void Main()
{
Copy("/tmp/foo", "/tmp/bar", new FileCopyUI());
}
As a variation of the theme, you can use events, delegates or whatever the language of your choice provides.
In C, this could be a function pointer, in C++ a reference to a class I guess.
What about this approach [pseudo-code]:
UIClass
{
//
// Some code
//
bool fileCopied = false;
do {
try {
fileCopied = CopyFile(fileName);
} catch (FileExists) {
//
// Ask "File exists! Overwrite?" If "No", exit do-loop
//
} catch (FileLocked) {
//
// Ask "File Locked! Repeat?", If "No", exit do-loop
//
} catch (etc...) {
//
// etc.
//
}
} while (!fileCopied);
//
// Some code
//
}
LogicClass
{
//
// Some code
//
bool CopyFile(string fileName)
{
//
// copy file
//
}
//
// Some code
//
}

Resources