HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not...

185
NORGES TEKNISK-NATURVITENSKAPELIGE UNIVERSITET FAKULTET FOR INFORMASJONSTEKNOLOGI, MATEMATIKK OG ELEKTROTEKNIKK HOVEDOPPGAVE Kandidatens navn: Karine Sørby Fag: Datateknikk Oppgavens tittel (norsk): Oppgavens tittel (engelsk): Relationship between security and safety in a security-safety critical system: Safety consequences of security threats Oppgavens tekst: Security and safety are two terms representing two different domains, but with a lot in common. While safety traditionally is related to chemical, aerospace, nuclear power and process industry, security concerns itself with programmable systems, in many cases applications developed for use on the Internet. However, many systems in the process industry make use of computerized systems for monitoring or controlling the system and even as part of the system itself. Furthermore, traditionally Internet applications are becoming more complex and include systems such as Telemedicine systems, where one needs to consider the human factors as well. One problem with the terms safety and security is the variety of definitions provided. They are both used to characterize computer systems when used in a context where reliance is placed upon them. The main objective of this thesis is to look into these two domains in order to clarify similarities and differences, and most importantly dependencies between the security and the safety of a system. The main scope for the study is to concretize how the two terms interact and to propose a development process for systems where both factors are present. We will look into how to combine risk analysis and system develop- ment for such a combined system, hereafter denoted a security-safety critical system, by developing a small prototype. The prototype system will be used as a means to study the properties of a security-safety critical system, and in particular the safety consequences of security threats. The prototype system will be implemented using LEGO Mindstorms and Sony AIBO robots, and wireless communication will be used as one of the communication channels. This in order to emphasize the difference between wired and wireless communi- cation in terms of safe and secure systems as wireless communication is increasingly used in systems today in order to make them more flexible and to reduce cost. Oppgaven gitt: 20. januar 2003 Besvarelsen leveres innen: 28. juli 2003 Besvarelsen levert: 24. juli 2003 Utført ved: Institutt for datateknikk og informasjonsvitenskap Veileder: Siv Hilde Houmb Trondheim, 24. juli 2003 Tor St˚ alhane Faglærer

Transcript of HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not...

Page 1: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

NORGES TEKNISK-NATURVITENSKAPELIGE UNIVERSITET

FAKULTET FOR INFORMASJONSTEKNOLOGI, MATEMATIKK OG ELEKTROTEKNIKK

HOVEDOPPGAVE

Kandidatens navn: Karine Sørby

Fag: Datateknikk

Oppgavens tittel (norsk):

Oppgavens tittel (engelsk): Relationship between security and safety in a security-safetycritical system: Safety consequences of security threats

Oppgavens tekst:

Security and safety are two terms representing two different domains, but with a lotin common. While safety traditionally is related to chemical, aerospace, nuclear powerand process industry, security concerns itself with programmable systems, in many casesapplications developed for use on the Internet. However, many systems in the processindustry make use of computerized systems for monitoring or controlling the system andeven as part of the system itself. Furthermore, traditionally Internet applications arebecoming more complex and include systems such as Telemedicine systems, where oneneeds to consider the human factors as well.

One problem with the terms safety and security is the variety of definitions provided. Theyare both used to characterize computer systems when used in a context where reliance isplaced upon them. The main objective of this thesis is to look into these two domains inorder to clarify similarities and differences, and most importantly dependencies betweenthe security and the safety of a system. The main scope for the study is to concretizehow the two terms interact and to propose a development process for systems where bothfactors are present. We will look into how to combine risk analysis and system develop-ment for such a combined system, hereafter denoted a security-safety critical system, bydeveloping a small prototype. The prototype system will be used as a means to study theproperties of a security-safety critical system, and in particular the safety consequences ofsecurity threats. The prototype system will be implemented using LEGO Mindstorms andSony AIBO robots, and wireless communication will be used as one of the communicationchannels. This in order to emphasize the difference between wired and wireless communi-cation in terms of safe and secure systems as wireless communication is increasingly usedin systems today in order to make them more flexible and to reduce cost.

Oppgaven gitt: 20. januar 2003Besvarelsen leveres innen: 28. juli 2003Besvarelsen levert: 24. juli 2003Utført ved: Institutt for datateknikk og informasjonsvitenskapVeileder: Siv Hilde Houmb

Trondheim, 24. juli 2003

Tor StalhaneFaglærer

Page 2: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties
Page 3: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Abstract

The distinction between safety and security is not always clear. Safety and security are normallyregarded as representing distinct properties and are treated separately, but at the same time thetwo terms often get intertwined and mixed up with one another.

This report presents a study of the relationship between safety and security and focuses inparticular on the consequences that security threats may have on the safety of a system. Thestudy is conducted by performing risk analysis on a prototype of a security-safety critical system,where a security-safety critical system is defined as a system where a security critical systemmonitors and controls a safety critical system.

The prototype consists of a safety critical cutting robot placed inside a safety zone, and asecurity critical control system controlling the cutting robot. The cutting robot is representedby a LEGO Mindstorms robot, whereas the control system consists of a PC controller and aSony AIBO robot. The AIBO is provided with a camera with which it monitors the area infront of the entrance into the safety zone. The PC controller, which is the link between theLEGO system and the AIBO, communicates with the AIBO through wireless LAN and withthe LEGO Mindstorms robot through infrared (IR) signals.

A development process for security-safety critical systems is proposed, and applied to the devel-opment of the prototype. The proposed development process integrates risk management intothe development process and is therefore an integrated system development and risk manage-ment process. Methods for analyzing risk were originally developed for the safety domain. Inthis thesis a modified HAZOP adapted by Winter et al. for use in security critical systems, theSecurity-HazOp, is used.

The experience gained during the development of the prototypeis that while security threatsrelated to some of the security attributes affect the safety of the system, others have no directnor even indirect effect on the safety. The security attribute “confidentiality” was found to beirrelevant in terms of safety. The “integrity”, “availability” and “authenticity” attributes, how-ever, were identified to be indirectly related to the safety of a system. Threats to one of theseattributes may lead to system failure in the control system of a security-safety critical system,and hence possibly also an accident.

i

Page 4: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

ii

Page 5: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Preface

This master’s thesis report is written for the Department of Computer and Information Science(IDI) at the Norwegian University of Science and Technology (NTNU).

I would like to thank my supervisor, Ph.D. student Siv Hilde Houmb, for useful help andguidance throughout the project. She has shown an incredible enthusiasm and interest in mywork, and has given me valuable hints and feedback. I would also like to thank Pavel Petrovicfor helping me with the implementation of the system, and Professor Tor Stalhane for help-ful advice. In addition, I would like to give my thanks to my fellow students Kine KvernstadHansen, Christian Holme and Ørjan Markhus Lillevik for valuable comments on contents andlanguage of the report.

Trondheim, July 24, 2003

Karine Sørby

iii

Page 6: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

iv

Page 7: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Contents

1 Introduction 11.1 Motivation and background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Problem Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

1.3 Related work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.4 Structure of the report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2 Safety 72.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72.2 Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

2.3 Ontology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.4 Designing and implementing safe systems . . . . . . . . . . . . . . . . . . . . . . 11

3 Security 13

3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133.2 Standards and History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133.3 Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

3.4 Ontology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153.5 Security threats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

3.5.1 Threats to data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

3.6 Designing and implementing secure systems . . . . . . . . . . . . . . . . . . . . . 19

4 Risk Management 214.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

4.2 Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214.3 Risk Management Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224.4 Risk Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

4.4.1 Preliminary Hazard Analysis (PHA) . . . . . . . . . . . . . . . . . . . . . 234.4.2 Hazard and Operability Analysis (HazOp) . . . . . . . . . . . . . . . . . . 244.4.3 Fault Tree Analysis (FTA) . . . . . . . . . . . . . . . . . . . . . . . . . . 24

4.4.4 Failure Modes, Effects (and Criticality) Analysis (FME(C)A) . . . . . . . 254.5 Risk Estimation and Risk Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . 254.6 Treat Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

5 Wireless Networking 295.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295.2 Types of wireless systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

5.2.1 Infrared systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305.2.2 Wireless LAN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

5.3 Security issues in Wireless LANs . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

v

Page 8: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

6 SONY AIBO 33

6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

6.2 Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

6.3 Programming AIBO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

6.3.1 OPEN-R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

7 LEGO Mindstorms 37

7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

7.2 Components of LEGO Mindstorms . . . . . . . . . . . . . . . . . . . . . . . . . . 37

7.2.1 RCX Brick: The Robotics Command eXplorer . . . . . . . . . . . . . . . 37

7.2.2 Motors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

7.2.3 Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

7.2.4 IR Transmitter tower . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

7.3 Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

7.4 Programming with LEGO Mindstorms . . . . . . . . . . . . . . . . . . . . . . . . 39

7.4.1 BrickOS (LegOS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

8 Development Process 41

8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

8.2 IEC 61508 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

8.3 CORAS model based risk assessment . . . . . . . . . . . . . . . . . . . . . . . . . 43

8.3.1 The risk management process . . . . . . . . . . . . . . . . . . . . . . . . . 44

8.3.2 The integrated risk management and system development process . . . . 45

8.4 Security-Safety Lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

9 Security-Safety Critical System 49

9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

9.2 Concept and Overall Scope Definition . . . . . . . . . . . . . . . . . . . . . . . . 49

9.2.1 System description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

9.2.2 Updated system description after PHA and Security-HazOP . . . . . . . . 53

9.3 Preliminary Hazard Analysis (PHA) . . . . . . . . . . . . . . . . . . . . . . . . . 55

9.4 Requirement Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

9.4.1 Functional Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

9.4.2 Non-Functional Requirements . . . . . . . . . . . . . . . . . . . . . . . . . 60

9.4.3 Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

9.5 Identify Security Threats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

9.5.1 Security-HAZOP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

9.5.2 Execution of the Security-HazOp . . . . . . . . . . . . . . . . . . . . . . . 69

9.5.3 Results of the Security-HazOp . . . . . . . . . . . . . . . . . . . . . . . . 69

9.6 Analyse Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

9.6.1 Identify Safety Consequences . . . . . . . . . . . . . . . . . . . . . . . . . 71

9.6.2 Identify Likelihood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

9.6.3 Estimate Level of Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

9.7 Evaluate Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

9.8 Treat Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

9.8.1 Update system description and requirements . . . . . . . . . . . . . . . . 77

9.9 System Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

9.9.1 Overall Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

9.9.2 AIBO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

vi

Page 9: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.9.3 LEGO System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 839.9.4 PC Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849.9.5 Collaboration Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

9.10 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 909.10.1 Choice of Programming Language and Development Environment . . . . 919.10.2 AIBO Network Configuration and Settings . . . . . . . . . . . . . . . . . 919.10.3 The PO Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

9.11 Testing and Safety Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

10 Safety - Security 9710.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9710.2 The Meaning of Safety and Security . . . . . . . . . . . . . . . . . . . . . . . . . 9710.3 The Relationship between Safety and Security . . . . . . . . . . . . . . . . . . . . 98

10.3.1 Similarities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9810.3.2 Differences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9810.3.3 Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

10.4 Security-Safety Critical Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9910.4.1 Introduction of Computers to Safety-Critical Control Systems . . . . . . . 10010.4.2 Security Properties in a Safety Context . . . . . . . . . . . . . . . . . . . 100

10.5 Safety Consequences of Security Threats . . . . . . . . . . . . . . . . . . . . . . . 101

11 Conclusion and Further Work 103

A Glossary 105

B Abbreviations 109

C Security-HazOp Tables 111

D Risk Analysis Tables 119

E Post office - detailed description 127

F Operating Manual 131

G Source Code 133

vii

Page 10: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

viii

Page 11: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

List of Figures

1.1 Structure of the report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2.1 Safety Ontology - relationships between terms used in safety . . . . . . . . . . . . 10

3.1 Security Ontology - relationships between terms used in security . . . . . . . . . 16

3.2 Threats to data, hardware and software . . . . . . . . . . . . . . . . . . . . . . . 17

3.3 Normal flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

3.4 Interruption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

3.5 Interception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

3.6 Modification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

3.7 Fabrication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

4.1 Risk Management Process [4] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

4.2 FTA fault tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

5.1 802.11 and the OSI (Open System Interconnection) model [9] . . . . . . . . . . . 31

6.1 AIBO ERS-220A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

6.2 Wireless LAN network configurations [20]. . . . . . . . . . . . . . . . . . . . . . . 34

7.1 The LEGO Mindstorms RCX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

7.2 LEGO Mindstorms IR Tower . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

7.3 RCX Architecture with brickOS [8] . . . . . . . . . . . . . . . . . . . . . . . . . . 40

8.1 Overall safety lifecycle, IEC 61508 [33] . . . . . . . . . . . . . . . . . . . . . . . . 42

8.2 The CORAS framework [11] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

8.3 Part of the integrated risk management and system development process [11] . . 46

8.4 Security-safety lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

9.1 Concept and Overall Scope Definition . . . . . . . . . . . . . . . . . . . . . . . . 50

9.2 Example architecture of a security-safety critical system . . . . . . . . . . . . . . 50

9.3 The security-safety critical system . . . . . . . . . . . . . . . . . . . . . . . . . . 519.4 Components of the Security-Safety critical system . . . . . . . . . . . . . . . . . 53

9.5 Preliminary Hazard Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

9.6 Risk Management: Safety and security requirements . . . . . . . . . . . . . . . . 58

9.7 Elicitation of safety and security requirements . . . . . . . . . . . . . . . . . . . . 61

9.8 Use case diagram: Overall system functionality . . . . . . . . . . . . . . . . . . . 63

9.9 Decomposed use case diagram: Stop cutting robot . . . . . . . . . . . . . . . . . 65

9.10 Decomposed use case diagram: Start cutting robot . . . . . . . . . . . . . . . . . 679.11 Identify security threats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

9.12 Analyse risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

ix

Page 12: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.13 Identify safety consequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719.14 Identify likelihood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 729.15 Estimate level of risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 749.16 Evaluate risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 749.17 Treat risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759.18 Update system description and requirements . . . . . . . . . . . . . . . . . . . . 779.19 Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789.20 Overall architecture of the system . . . . . . . . . . . . . . . . . . . . . . . . . . 799.21 Deployment of the components in the system . . . . . . . . . . . . . . . . . . . . 809.22 State diagram: AIBO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 819.23 Component diagram: BallTrackingHead . . . . . . . . . . . . . . . . . . . . . . . 819.24 State diagram: LEGO system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 839.25 Factory application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849.26 The control window on the PC controller . . . . . . . . . . . . . . . . . . . . . . 859.27 State diagram: PC Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 869.28 Component diagram: Ball3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 869.29 State diagram: Post Office Thread . . . . . . . . . . . . . . . . . . . . . . . . . . 879.30 State diagram: GUI Thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 879.31 State diagram: AIBO Thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 889.32 Collaboration diagram: Green man . . . . . . . . . . . . . . . . . . . . . . . . . . 889.33 Collaboration diagram: Gate open . . . . . . . . . . . . . . . . . . . . . . . . . . 899.34 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 909.35 The factory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 909.36 AIBO network configuration [20] . . . . . . . . . . . . . . . . . . . . . . . . . . . 919.37 The PO protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 949.38 Testing and Safety validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

E.1 Detailed usage of IR tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128E.2 Sequence diagram: Functionality of the PO (Post Office) thread . . . . . . . . . . 130

x

Page 13: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

List of Tables

4.1 Guideword interpretations for PES . . . . . . . . . . . . . . . . . . . . . . . . . . 24

4.2 Consequence values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264.3 Likelihood ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

4.4 Risk Class Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

4.5 Risk classification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

8.1 Activities of the CORAS risk management process [31] . . . . . . . . . . . . . . 45

8.2 Steps of the security-safety lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . 48

9.1 Preliminary Hazard Analysis (PHA) Results . . . . . . . . . . . . . . . . . . . . . 55

9.2 Preliminary Hazard Analysis (PHA) Results cont. . . . . . . . . . . . . . . . . . 56

9.3 Main use cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629.4 Actors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

9.5 Use case specification: Open gate . . . . . . . . . . . . . . . . . . . . . . . . . . . 639.6 Use case specification: Close gate . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

9.7 Use case specification: Lock gate . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

9.8 Use case specification: Unlock gate . . . . . . . . . . . . . . . . . . . . . . . . . . 649.9 Use case specification: Notify PC controller . . . . . . . . . . . . . . . . . . . . . 65

9.10 Use case specification: Stop initiated by Off button in entrance area . . . . . . . 659.11 Use case specification: Stop initiated by stop button in control window . . . . . . 66

9.12 Use case specification: Stop if connection between AIBO and PC lost . . . . . . . 66

9.13 Use case specification: Stop if connection between PC and LEGO system lost . . 669.14 Use case specification: Start initiated by On button in entrance area . . . . . . . 67

9.15 Use case specification: Start initiated by start button in control window . . . . . 679.16 Basic guidewords and attributes in security-HazOp . . . . . . . . . . . . . . . . . 69

9.17 Guidewords, components and attributes used in the security-HazOp . . . . . . . 69

9.18 Documentation form for the Security-HazOp . . . . . . . . . . . . . . . . . . . . 709.19 AIBO network settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

C.1 Results of Security-HazOp - Breaches of confidentiality . . . . . . . . . . . . . . . 112C.2 Results of Security HazOp - Breaches of integrity . . . . . . . . . . . . . . . . . . 113

C.3 Results of Security HazOp - Breaches of integrity cont. . . . . . . . . . . . . . . . 114

C.4 Results of Security-HazOp - Breaches of availability . . . . . . . . . . . . . . . . 115C.5 Results of Security-HazOp - Breaches of availability cont. . . . . . . . . . . . . . 116

C.6 Results of Security-HazOp - Breaches of authenticity . . . . . . . . . . . . . . . . 117

D.1 Analyse Risk - Breaches of confidentiality . . . . . . . . . . . . . . . . . . . . . . 120

D.2 Analyse Risk - Breaches of integrity . . . . . . . . . . . . . . . . . . . . . . . . . 121

D.3 Analyse Risk - Breaches of integrity cont. . . . . . . . . . . . . . . . . . . . . . . 122D.4 Analyse Risk - Breaches of availability . . . . . . . . . . . . . . . . . . . . . . . . 123

xi

Page 14: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

D.5 Analyse Risk - Breaches of availability cont. . . . . . . . . . . . . . . . . . . . . . 124D.6 Analyse Risk - Breaches of authenticity . . . . . . . . . . . . . . . . . . . . . . . 125

G.1 File content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133G.2 File content AIBO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134

xii

Page 15: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Chapter 1

Introduction

1.1 Motivation and background

Safety and security are normally regarded as representing distinct properties and are treatedseparately, but at the same time the two terms often get intertwined and mixed up with oneanother [14]. Some languages actually use the same word for both safety and security, likeSicherheit (in German) and sikkerhet (in Norwegian). Further, in many dictionaries, safetyis defined in terms of security and visa versa. This indicates that there are some conceptualsimilarities between the safety and security of a system, even if the existing definitions of theterms have been developed separately.

The distinction between safety and security is not always clear. Both safety and security dealwith threats, but the type of threats differs. According to Leveson [46], threats to safety meanthreats to life and property, while security threats represent threats to privacy or national secu-rity. Accordingly, safety can be defined as freedom from accidents and losses [46], and a safetycritical system is therefore a system that by failing can cause harm to life, property or envi-ronment. Further, security can be defined as the preservation of confidentiality, integrity andavailability, [39], and a security critical system is a system whose assets may contain vulnerabil-ities that might be exploited by one or more threats.

Risk is used to describe the likelihood of occurence and the consequence of a threat. Both in thecase of safety and security threats one needs a tool to assess risks. Risk assessment provides ameans for eliminating or reducing risks. The risk management process was originally developedfor use within the safety domain. However, because of the similarities between safety andsecurity, these techniques have been adapted to the security domain. The EU funded CORASproject [17] has developed a framework for risk analysis of security critical systems based onexperience and methods from the safety domain.

With the conventional non-programmable hardware control systems, failure in the system itselfis generally the source of risk. These days more and more computerized systems are usedfor monitoring and controlling safety critical systems. Use of computerized systems increasesthe complexity and introduces the notion of vulnerabilities to the system. Hence, the systemcan be characterized as both safety and security critical since a failure of the system causedby an explotion of a vulnerability in the software of the computerized system can lead to anaccident. For systems where security critical systems are used to control safety critical systems,the relationship between safety and security should be considered in order to specify appropriateways to handle risks.

1

Page 16: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Introduction

1.2 Problem Description

Security and safety are two terms representing two different domains, but with a lot in common.While safety traditionally is related to chemical, aerospace, nuclear power and process industry,security concerns itself with programmable systems, in many cases applications developed foruse on the Internet. However, many systems in the process industry make use of computerizedsystems for monitoring or controlling the system and even as part of the system itself. Further-more, traditionally Internet applications are becoming more complex and include systems suchas Telemedicine systems, where one needs to consider the human factors as well.

One problem with the terms safety and security is the variety of definitions provided. They areboth used to characterize computer systems when used in a context where reliance is placedupon them. The main objective of this thesis is to look into these two domains in order toclarify similarities and differences, and most importantly dependencies between the securityand the safety of a system. The main scope for the study is to concretize how the two termsinteract and to propose a development process for systems where both factors are present.We will look into how to combine risk analysis and system development for such a combinedsystem, hereafter denoted a security-safety critical system, by developing a small prototype. Theprototype system will be used as a means to study the properties of a security-safety criticalsystem, and in particular the safety consequences of security threats. The prototype system willbe implemented using LEGO Mindstorms and Sony AIBO robots, and wireless communicationwill be used as one of the communication channels. This in order to emphasize the differencebetween wired and wireless communication in terms of safe and secure systems as wirelesscommunication is increasingly used in systems today in order to make them more flexible andto reduce cost.

1.3 Related work

Adaptation of risk assessment methodologies to the security domain has recently experienced anincreasingly interest and attention. Several methodologies exist, such as SEISMED – guideline onIT security risk analysis for health care IT and security personnel [16], RAMME – a risk analysismodel for a medical environment [27], and CRAMM – CCTA risk analysis and managementmethodology [6]. All these methodologies are applicable within the health care domain, howeverCRAMM is intended for risk analysis of computerized systems in general. CRAMM is developedby the British Government’s Central Computer and Telecommunication Agency (CCTA) in orderto provide a structured and consistent approach to computer management of all systems, and isby the UK National Health Service considered as the standard for risk analysis within systemssupporting healtcare.

Adaptation of risk assessment to the security domain was also one of the main objectives ofthe EU funded CORAS project [17]. CORAS has developed a framework for modelbased riskassessment of security-critical systems, where one of the foundation pilars is the integrated riskmanagement and system development process.

CORAS further emphasized the integration of UML as input to and as a tool for documentingresults from risk assessment. UMLsec [44] is a UML profile for secure systems development.UMLsec is an extension of UML that allows for the expression of security relevant informationwithin the diagrams in a system specification. Also concerned with the use of UML in a se-curity context, SecureUML [63] is a UML-based modelling language for model-driven securityconcentrating on role-based access control within the design stage of a development process.

2

Page 17: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

1.3. RELATED WORK

Several attempts have been made on explaining and distinguishing security from safety, e.g.Burns et al. in [14], Stavridou et al. in [59], and by Leveson in [45]. Definitions of safetyare closely related to the term dependability. In [41], dependability is used to describe what wedenote as safety in this work. In [41] Jonsson et al. aims at developing a unified terminology andunderstanding of security and dependability impairments. Similarly, in [40] Jonsson illustrateshow the aspects of traditional security could be integrated with existing dependability concepts.

3

Page 18: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Introduction

1.4 Structure of the report

Figure 1.1 illustrates the structure of this report and suggests the order in which the chaptersshould be read. The six chapters situated in the big circle provide background information aboutthe relevant topics. These chapters can be read in any order, but it is recommended that thesafety and security chapters are read before the chapter on risk management.

4 Risk Management

5 Wireless Networking

2 Safety

7 LEGO Mindstorms

6 Sony AIBO

3 Security

10 Safety - Security

9 Security-Safety Critical System

8 Development Process

1 Introduction

11 Conclusion and Further Work

Figure 1.1: Structure of the report

4

Page 19: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

1.4. STRUCTURE OF THE REPORT

Chapter 1: IntroductionIn this chapter we introduce the most important concepts addressed in this report, provide mo-tivation for our work, and present the problem description, as well as related work.

Chapter 2: SafetyThis chapter presents a brief introduction to the concepts of safety and safety critical systems.A safety terminology and its ontology are specified and adapted to fit within the security-safetydomain.

Chapter 3: SecurityThis chapter presents a brief introduction to the concepts of security and security critical sys-tems. A security terminology and its ontology are specified and adapted to fit within thesecurity-safety domain.

Chapter 4: Risk Management and AssessmentThis chapter presents the risk management process defined in the Australian standard AS/NZS4360:1999, and briefly describes the most important risk analysis methods.

Chapter 5: Wireless NetworkingThis chapter presents a brief introduction to wireless networking, with emphasis on wirelessLAN and infrared systems.

Chapter 6: SONY AIBOThis chapter presents AIBO, the Sony entertainment robot, along with ways in which to com-municate with and program the AIBO.

Chapter 7: LEGO MindstormsThis chapter presents the components of LEGO Mindstorms, as well as a description of com-munication and programming issues.

Chapter 8: Development ProcessThis chapter presents the proposed development process used for the prototype in this work.Descriptions of the safety lifecycle of IEC 61508 and the CORAS integrated risk managementand system development process are also provided, since our development process is based onthese two.

Chapter 9: Security-Safety Critical SystemThis chapter illustrates the proposed development process using a prototype of a security-safetycritical system. The prototype makes use of a LEGO Mindstorms robot and a Sony AIBO,which communicates through a wireless network.

Chapter 10: Safety-SecurityIn this chapter we discuss the relationship between safety and security based on experiencesgained during the development of a security-safety critical system, together with existing defi-nitions and related work in the security and safety domains.

5

Page 20: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Introduction

Chapter 11: Conclusion and Further WorkThis chapter concludes the report by presenting the conclusion and suggestions for further work.

6

Page 21: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Chapter 2

Safety

2.1 Introduction

Safety is according to Leveson [46] “freedom from accidents or losses”. The term “systemsafety” may have first been used at a seminar conducted by the Flight Safety Foundation in1954, where C. O. Miller, an aviation safety pioneer, wrote the paper “Applying Lessons Learnedfrom Accident Investigations to Design Through a Systems Safety Concept” [46].

When the first standard for system safety, the MIL-STD-882, came in 1969, the Air Force hadlong experienced problems with aircraft accidents. Most of the accidents had been blamed on thepilot, but many flight engineers argued that the cause of the accidents was not that simple, andthat safety had to be designed and built into the aircraft. This theory was strengthened when theAir Force began to develop intercontinental ballistic missiles (ICBMs) which frequently blew up,and no pilots were to blame [46]. Accompanying the MIL-STD-882, the Department of Defence(DoD) made a system safety program mandatory for all DoD-procured products and systems.In the 1970s, as a result of computers becoming increasingly important in complex systems,concern about software safety began to emerge in DoD and NASA (National Aeroneutics andSpace Administration) programs, and gradually also in the commercial industry.

There are two ways in which a computer can control the safety of a system or device; either bydirect control where the computer makes the decisions, or by indirect control where the computergenerates data but leaves the decision-making to the human-controller. Obviously, there is aserious risk in relying on the computer to make the right decisions at all times, especiallyin potentially dangerous processes. This danger of overreliance on the accuracy of computeroutputs and databases is not only concerned with direct control, but is also applicable whensoftware is used in design analysis, when safety-critical data is stored in computer databases,and when software-generated data is used to make safety-critical desicions [46]. In these cases,the human-controller makes the final decisions, but on the basis of computer generated data.

A system is defined to be safety critical if it by failing can cause harm to life, property or en-vironment [66]. A widely used standard for guiding the development of safety critical systemsis the IEC 61508 [33] standard from The International Electrotechnical Commision (IEC). TheIEC 61508 (Functional safety of electrical/electronic/ programmable electronic safety-relatedsystems) covers all safety-related systems that are electrotechnical in nature, including elec-tromechanical systems, solid-state electronic systems and computer-based systems. This genericstandard can be used either directly as a standalone standard, or as a basis for the development

7

Page 22: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Safety

of sector standards. The IEC 61508 safety development lifecycle is further described in chapter8.2.

To identify the safety requirements of a system, risk assessment and management is important.Through risk assessment the (potential) hazards of the system are identified and alternativetreatments are proposed. See chapter 4 for further details on risk assessment and management.

2.2 Terminology

Terms used in the safety domain may have several different interpretations, often dependent onthe conceptual framework in which they are applied. This section describes the safety termi-nology used throughout this report in order to establish a consistent and clearly defined set ofterms that fits into the security-safety framework associated with this report.

Accident - an undesired and unplanned (but not necessarily unexpected) event that results in(at least) a specified level of loss [46].

Control system - used to determine the operation of some form of equipment or plant [61].

New definition: Control system - used to monitor and protect a safety critical system.

Error - a deviation from the required operation of the system or subsystem [61].

Failure - termination of the ability of a functional unit to perform a required function [33].

Fault - abnormal condition that may cause a reduction in, or loss of, the capability of a func-tional unit to perform a required function [33].

Harm - physical injury or damage to the health of people either directly or indirectly as a resultof damage to property or to the environment [33].

Hazard - a state or set of conditions of a system that, together with other conditions in theenvironment of the system, will lead to an accident [46].

Hazardous situation - circumstance in which a person is exposed to hazard(s) [33].

Hazardous event - hazardous situation which results in harm [33].

Incident - an unintended event or sequence of events that does not result in loss, but, underdifferent circumstances, has the potential to do so [61].

Interlock mechanism - mechanism which ensures that potentially hazardous actions are onlyperformed at times when they are safe [61].

Loss - any negative consequence, financial or otherwise [4].

8

Page 23: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

2.3. ONTOLOGY

Monitoring system - monitoring part of a control system.

Protection system - a system that uses sensors to detect fault conditions and produce outputsto mitigate their effects [61].

New definition: Protection system - protective part of a control system.

Risk - a combination of the likelihood of an accident and the severity of the potential conse-quences [46].

New definition: Risk - a combination of the likelihood of a security threat and the severity ofthe potential safety consequences.

Safeguard - a practice, procedure or mechanism that reduces risk [38].

Safety - freedom from accidents or losses [46].

Safety critical system - a system that by failing can cause harm to life, property or environ-ment [66].

Safety lifecycle - necessary activities involved in the implementation of safety-related systems,occurring during a period of time that starts at the concept phase of a project and finishes whenall of the E/E/PE1 safety-related systems, other technology safety-related systems and externalrisk reduction facilities are no longer available for use [33].

Stakeholder - an individual, team, or organization (or classes thereof) with interest in, or con-cerns relative to, a system [35].

System - a set of components that acts together as a whole to achieve some common goal,objective or end [46].

System environment - a set of components that is not part of the system but whose behaviorcan affect the system state [46].

Safety requirements specification - specification containing all the requirements of the safetyfunctions that have to be performed by the safety-related system [33].

2.3 Ontology

The intention of this section is to establish a precise and common understanding of the relation-ships between the safety related terms used in this work. The ontology, shown in figure 2.1, isbased on [61] and the definitions provided in the previous section.

A safety critical system includes a safety zone and a control system. The control system, whichconsists of a monitoring system and a protection system, monitors and protects the safety

1electical/electronic/programmable electronic

9

Page 24: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Safety

zone. The protection system consists of one or more safeguards, which use actuators to preventexposure to danger [61]. The monitoring system consists of one or more interlock mechanisms,which use sensors to detect the state of the system in order to detect dangerous conditions. Thesafety requirements specification identifies potential hazards of the system, and defines/enforcesnecessary safeguards and interlock mechanisms to ensure the safety. The safety requirementsare influenced by safety standards and the safety policy(ies) of the organization, and by thestakeholders of the system. Hazards may lead to accidents, and are often the result of faults inthe system. Faults may lead to errors. If an error causes the system as a whole to deviate fromits intended operation it is called a system failure. The risk of an accident is characterized bytwo factors, the likelihood of occurence and the consequence level of the accident.

Safety requirements

Fault

Actuators

Safeguards Interlock

mechanisms

System Failure

Error

Safety critical system

Sensors

Monitoring system

Protection system

Hazard

Safety policy

Risk

Safety standard

Loss Accident Safety

Consequence Likelihood

Stakeholder

May contain

May lead to

May lead to

ensures

enforces influences

identifies

May lead to

Control system

detects

Safety zone

protects monitors

1

1..*

1 1

1 1

1

1

1

1

1..*

1..*

1..*

1..*

1..*

1..*

influences 1..* 1..*

1..* 1

Figure 2.1: Safety Ontology - relationships between terms used in safety

10

Page 25: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

2.4. DESIGNING AND IMPLEMENTING SAFE SYSTEMS

2.4 Designing and implementing safe systems

According to Isaksen et al. [36], software in itself cannot cause an accident. It is when thesoftware is used to control potensially dangerous systems it becomes safety-critical.

When designing for safety it is not enough to consider only the software components of thesystem. All aspects of the system must be considered, including hardware devices, communica-tion links and power supply, as well as the human users of the system. Since the environmentin which the system will operate in is of vital importance, the system should be analysed in arelevant setting to get a realistic picture of the safety threats. What is part of the system andwhat is part of the environment is determined by the system boundaries. The system designershould define these boundaries such that all conditions related to the safety of the system areincluded in the system.

To make a system safe, it is not enough to identify and assess the hazards. To be of any use, theinformation gained from risk analysis must be used as input to the design [46]. However, safetyis not the only goal when designing and implementing systems. There will always be a treadeoffbetween the safety of the system and the system cost, effectiveness and performance. Accordingto Leveson [46], designing a system to protect against all hazards, no matter how perverse orremote, might require making so many compromises in functionality and other goals that thesystem is not worth building at all. Also, the complexity of a system may be an obstacle forsafety, as complexity often results in design errors, faults and risk of human errors caused bymisunderstandings. Thus, a system can never be considered absolutely safe, but a goal in systemdesign should be to make the system adequately safe for its given role [61].

11

Page 26: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

12

Page 27: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Chapter 3

Security

3.1 Introduction

According to ISO 13335, IT security comprises all aspects related to defining, achieving, andmaintaining confidentiality, integrity, availability, non-repudiation, accountability, authenticityand reliability [38]. This definition is here also applied to define information security.

As defined in Chapter 2, a system is a set of components that act together as a whole toachieve some common goal, objective or end [46]. Using this definition, an information system,which is a subset of system, consists of people, machines and methods for collecting, processing,transmitting and disseminating data. An IT system represents the computerized part of theinformation system.

Crucial decisions in organizations depend on accurate, timely data and correct processing. Withtodays increasing dependency on information systems and services, the organizations are morevulnerable to security threats than before [39]. The effects of security incidents can be catas-trophic. Therefore, organizations must proactively anticipate the various types of threats andfocus their attention on the threats of highest risk [1]. To reduce the chance of vulnerabilitiesin a system, security should be considered already in its requirements specification and designstage.

A system can only be trusted in relation to a security policy [54]. A trusted system is a systemthat employs sufficient hardware and software integrity measures to allow its use for process-ing sensitive information [54]. A security policy specifies requirements related to the securityproperties that the system must provide, which should include confidentiality, authentication,non-repudiation, integrity, availability, accountability and reliability. The security policy shouldalso specify services like access control and security administration to ensure the security of thesystem.

3.2 Standards and History

International standardization began with the creation of the International Electrotechnical Com-mision (IEC) in 1906, and in 1947 delegates from 25 countries founded the International Organi-zation for Standardization (ISO) [37]. The first computer security standard, Trusted ComputerSystem Evaluation Criteria (TCSEC), was developed by the US Department of Defence (DoD)

13

Page 28: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security

in 1983, in response to military needs. In 1985, this standard was revised, and the main docu-ment of the revised standard is more popularly known as the “Orange Book” [64]. In Europe,the European Commision published the latest version of the Information Technology SecurityEvaluation Criteria (ITSEC) [65] in 1991, after joint development by the nations of France,Germany, the Netherlands, and the United Kingdom. In Canada, a combination of the ITSECand TCSEC approaches was published as the Canadian Trusted Computer Product EvaluationCriteria (CTCPEC), the latest version in 1993 [15].

Other standards have later been specified. The standards adopted for the security field inthis work are the ISO/IEC 17799 Information technology - Code of practice for informationsecurity management [39], and the ISO/IEC 13335 Information tecnology - Security techniques- Guidelines for the management of IT security [38].

3.3 Terminology

This section describes the security terminology used throughout this report. The definitionsspecified in ISO/IEC 17799 [39] and ISO/IEC 13335 [38] are specifically adjusted to the securityfield. Furthermore, the two standards define the security terms differently. Hence, in order toestablish a consistent and clearly defined set of terms that fits into the security-safety frameworkassociated with this report, we have adopted the best fitting terms from either of the standards,and specified new definitions when considered necessary.

Asset - anything that has value to the organization [38].(Major assets of computing systems: hardware, software and data.)

Accountability - the property that ensures that the actions of an entity may be traced uniquelyto the entity [38].

Authenticity - the property that ensures that the identity of a subject or resource is the oneclaimed [38].

Availability - the property that ensures that authorized users have access to information andassociated assets when required [39].

Confidentiality - the property that ensures that information is accessible only to those autho-rized to have access [39].

Integrity - the property that safeguards the accuracy and completeness of information andprocessing methods [39].

Impact - the result of an unwanted incident [38].

Information security - preservation of confidentiality, integrity, availability, authenticity, re-liability, accountability and non-repudiation. (Derived from the definition of IT security in [38].)

14

Page 29: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

3.4. ONTOLOGY

IT security policy - rules, directives and practices that govern how assets, including sensitiveinformation, are managed, protected and distributed within an organization and its IT systems[38].

Information system - consists of people, machines and methods for collecting, processing,transmitting and disseminate data. (Derived from the definition of system in [46].)

IT system - the computerized part of the information system. (Derived from the definition ofsystem in [46].)

Non-repudiation - the property that ensures the ability to prove an action or event has takenplace, so that this event or action cannot be repudiated later [38].

Reliability - the property of consistent intended behaviour and results [38].

Risk - the potential that a given threat will exploit vulnerabilities of an asset or group of assetsand thereby cause harm to the organization [38].

New definition: Risk - a combination of the likelihood of a security threat and the severity ofthe potential safety consequences. (This new definition ensures consistency with the definitionused in the safety domain.)

Safeguard - see definition in Chapter 2.

Security - See Information security.

Security critical system - a system whose assets contain vulnerabilities that might be ex-ploited.

System - see definiton in Chapter 2.

Threat - a potential cause of an unwanted incident which may result in harm to a system ororganization [38].

Unwanted incident - Incident such as loss of confidentiality, integrity and/or availability [32].

Vulnerability - a weakness of an asset or group of assets which can be exploited by one ormore threats [38].

3.4 Ontology

This section describes the relationships between the security related terms defined. The ontology,shown in Figure 3.1, is based on the standards ISO/IEC 13335 [38], ISO/IEC 17799 [39] and[46].

15

Page 30: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security

RIsk

Vulnerability

Security critical system

Threat

Safeguard

Environmental

Asset

Unwanted incident

Security requirements

Security policy

Security standard

Stakeholder

influences

influences

enforces

reduces

Consequence Likelihood

leads to

exploits

contains

System Information System

IT System

Deliberate/ intended

attack

Accidental/ unintended

attack

1..*

1..*

Protects against

reduces

0..*

1..*

1..*

1 1..* 1..*

enforces

1

1..*

1..*

1..*

1..* 1

1..*

1..*

1..*

1..*

Figure 3.1: Security Ontology - relationships between terms used in security

A security critical system is a system whose assets contain vulnerabilities that might be exploited.The vulnerabilities may include weaknesses in physical layout, hardware, software, information,procedures and administration. Single or multiple threats may exploit single or multiple vul-nerabilities. The threats can be environmental threats like earthquakes or fires, or they maybe of human origin, either deliberate or accidental. Security threats are further described inthe next section. The potential that a given threat will exploit a vulnerability introduces riskas it may lead to an unwanted incident. The risk is characterized by the combination of alikelihood value of the occurence of the unwanted incident and a consequence value to describethe severity of the potential consequences. Consequences might be damage to the IT system,destruction of assets, and loss of confidentiality, integrity, availability or authenticity. Securityrequirements aim at reducing the vulnerabilities by enforcing safeguards. Further, safeguardsreduce vulnerabilities, and hence risk, by protecting against unwanted incidents. Measurementof the consequences is helpful when determining the balance between the results of an unwantedincident and the cost of the safeguards to protect against unwanted incidents [38]. The securityrequirements are influenced by the security policy(ies) of the organization, thus indirectly alsoby the stakeholders of the system, and by security standards, such as ISO/IEC 13335 [38] andISO/IEC 17799 [39]. As described in the introduction to this chapter, an IT system is a part ofan information system, and an information system is a subset of system.

3.5 Security threats

According to ISO 13335 [38], a threat has the potential to cause an incident that may result inharm to a system or organization and its assets. A security threat can be as simple as interfering

16

Page 31: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

3.5. SECURITY THREATS

with a network’s normal operation or as complex as actively cracking the security and changingor taking control of network resources. A Denial of Service (DoS) attack, which prevents othersfrom using the system, is an example of interference with normal operation. Denial of Serviceattacks can take many forms, and the most common DoS attacks are SYN Flooding, SmurfAttacks, IP Spoofing, TearDrop and Ping of Death. Other types of threats to a network arebuffer overflow, trojan horses, intercepted transmissions, intruders and physical security. Formore details on these attacks, the reader is refered to [50].

There are several types of threats to a computer system or network. Threats can be of naturalor human origin, either intentional (deliberate) like eavesdropping, information modification,system hacking, malicious code, and theft, or non-intentional (accidental) like errors and ommi-sions, file deletion, incorrect routing, and physical accidents. Threats can also be environmental,such as natural disasters (earthquake, lightning, floods) or fire [38].

Intentional misuse, or attacks, can be classified into two categories; Passive attacks and activeattacks [58]. Passive attacks involve eavesdropping and monitoring, where the goal is to obtainaccess to information that is transmitted over a network or in a computing system [58]. As thistype of attacks does not involve any alteration of the data, they are very difficult to detect.Thus, prevention of these attacks is more effective than detection. Active attacks involve somemodification of the data stream or the creation of a false data stream, and are therefore easierto detect than passive attacks. Under this category of attacks we find masquerading, replay,modification of messages, and denial of service (DoS) [58].

A security threat can affect different properties of a system; availability, confidentiality, integrity,authenticity, non-repudiation, accountability and reliability [38]. In this report we will only con-sider the properties availability, integrity, confidentiality and authenticity. Which property isaffected depends on the type of threat. As figure 3.2 shows, different assets (hardware, softwareand data) may contain vulnerabilities which can be exploited by threats.

Theft

Interruption

Deletion

Theft

Modification

Interruption

Fabrication

Interception

THREATS TO

Data Hardware Software

Modification

Figure 3.2: Threats to data, hardware and software

3.5.1 Threats to data

This section describes the classes of threats associated with the flow of data in a system. Thethreats to the availability, confidentiality, integrity, and authenticity are illustrated in Figures3.4-3.7.

17

Page 32: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security

Normal flow: Figure 3.3 shows the normalflow of information from an information sourceto an information destination.

Threats to availability: If an asset of thesystem is destroyed or becomes unavailable orunusable, the information flow is interrupted,and hence the availability is threatened [58].(see Figure 3.4).

Threats to confidentiality: If an unautho-rized person or program gains access to an assetas shown in Figure 3.5 it is called interception,and the confidentiality of the authorized partyis compromised. Possible attacks are wiretap-ping and unauthorized copying of files or pro-grams.

Threats to integrity: If an unauthorized per-son or program gains access to and modifies anasset, it is a threat to integrity (see Figure 3.6).Examples of such attacks are changing of val-ues in a file, modifying the content of transmit-ted messages, and altering programs to changetheir behaviour [58].

Threats to authenticity: Insertion of coun-terfeit objects into the system by unauthorizedparties, as illustrated in Figure 3.7, is a threatto the authenticity of the system. This includesthe insertion of spurious messages in a networkor the addition of records to a file [58].

Source Destination

Figure 3.3: Normal flow

Source Destination

Figure 3.4: Interruption

Source Destination

Unauthorized party

Figure 3.5: Interception

Source Destination

Unauthorized party

Figure 3.6: Modification

Source Destination

Unauthorized party

Figure 3.7: Fabrication

18

Page 33: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

3.6. DESIGNING AND IMPLEMENTING SECURE SYSTEMS

3.6 Designing and implementing secure systems

A good design is essential for the development of secure systems, thus the principles of securedesign should be applied from the beginning of a project. Still, a poor implementation cancompromise the good design. Security needs to be applied not only to the system being developedbut also to tools and intermediate products as well as to the development process itself [62].

Examples of principles for secure design can be [62]:

- to keep the design as simple and small as possible;

- to base access decisions on permission rather than exclusion;

- to validate every access to every object;

- to use two or more keys to unlock a protection mechanism or two independent mechanismsthat must agree before allowing an action.

Identification of security requirements is essential, and for this there are three main sources;(1) Risk assessment, (2) Legal, statutory, regulatory and contractual requirements, and (3)Principles, objectives and requirements for information processing [39]. Further, a securitypolicy should be set for the organization which sets a clear policy direction and demonstratessupport for, and commitment to, information security [39].

One methodology for developing security-critical systems is the UMLsec [44]. The UMLsecapproach is an extension of UML that allows the expression of security-relevant informationwithin the diagrams in a system specification [44]. The standard UML extension mechanismsare used in order to specify the UMLsec in the form of a UML profile where stereotypes areused together with tags to formulate security requirements and assumptions on the systemenvironment. More information on UMLsec can be found in [43, 44].

In chapter 8.4, the development process lifecycle proposed for the developement of security-safetycritical systems is described. Security aspects are in this process included into the developmentprocess by the identification of security requirements and security threats.

19

Page 34: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

20

Page 35: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Chapter 4

Risk Management

4.1 Introduction

Risk management and the methods for risk analysis were originally developed for use withinthe safety domain. However, work is being done in adopting risk management and risk analysismethods to the security domain. CORAS (IST-2000-25031) [17], which is a research and tech-nological development project under the Information Society Technologies (IST) Programme,has as one of its main objectives: “To develop a practical framework, exploiting methods forrisk analysis developed within the safety domain, semiformal description methods, in particu-lar, methods for object- oriented modelling, and computerised tools for the above mentionedmethods, for a precise, unambiguous, and efficient risk analysis of security critical systems.”

An existing standard for risk management is the Australian Standard AS/NZS 4360:1999 Riskmanagement [4]. This standard provides a generic framework for the establishment and im-plementation of the risk management process. As it is independent of any specific industry, itshould be read in conjunction with other relevant standards. In order to support the challengesin security-safety critical systems we have refined the process for the security-safety domain.This is described in Chapter 8.4.

4.2 Terminology

The following definitions, based on AS/NZS 4360:1999 [4], are used in this report.

Risk analysis - a systematic use of available information to determine how often specifiedevents may occur and the magnitude of their consequences.

Risk assessment - the overall process of risk analysis and risk evaluation.

Risk evaluation - the process used to determine risk management priorities by comparing thelevel of risk against predetermined standards, target risk levels or other criteria.

Risk identification - the process of determining what can happen, why and how.

21

Page 36: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Risk Management

Risk management - the culture, processes and structures that are directed towards the effec-tive management of potential opportunities and adverse effects.

Risk management process - the systematic application of management policies, proceduresand practices to the tasks of establishing the context, identifying, analyzing, evaluating, treat-ing, monitoring and communicating risk.

Risk treatment - selection and implementation of appropriate options for dealing with risk.

4.3 Risk Management Process

Risk management is the process of establishing the context, identifying, analyzing, evaluating,treating, monitoring and communicating risks. The process, which is specified in AS/NZS 4360:1999 [4], is depicted in Figure 4.1. The goal of this process is to eliminate or reduce the risks inorder to minimize losses [4].

Identify Context

Analyze Risk

Estimate Level of Risk

Determine Consequence

Treat Risks

Determine Likelihood

Identify Risks

Evaluate Risks

Accept Risks

M o n

i t o r

a n d

R e

v i e

w

Yes

No

C o

m m

u n i

c a t

e a

n d

C o

n s u

l t

Figure 4.1: Risk Management Process [4]

In the first phase of the process, the context for the risk analysis is established. This includesthe strategic, organisational and risk management context, as well as criteria and structure ofthe analysis. The next phase is the identification of risks, answering the questions “what canhappen?” and “how can it happen?”. In the analyze risk phase, the level of risk is estimatedbased on estimates of likelihood and consequence of the risk. Following this phase, the risksare evaluated against the predefined acceptance criterias. Risks that are not accepted must betreated, which is done in the final phase of the risk management process.

The risk management process is an iterative process. In addition to iterations among the abovementioned phases, the whole process iterates through two additional and parallell sub processes.Monitoring and review is important to ensure that changes do not alter the risk priorities, andthat the management plan remains relevant [4]. Communication and consultation ensures a two

22

Page 37: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

4.4. RISK ANALYSIS

way dialogue between stakeholders in order to ensure a common understanding of the risk issues[4].

The risk management process should be applied early in the design phase of a new project.Safeguards are significantly less expensive to implement in the design phase than they would be ifincluded during or after the implementation phase. However, risk management is not a one-timetask. It is an ongoing activity and should also be an integrated part of the development processas well as the planning process of significant changes to existing systems [38]. Risk managementcan be supported by life-cycle models, which define project phases and deliverables. Chapter 8describes the development life cycle model used in this work.

4.4 Risk Analysis

Risk analysis is part of the risk management process. It includes identification of the sourcesof risk, their consequences and the likelihood of occurence. When analysing risks, information,which is helpful when evaluating and treating the risks, is gained. This information is used asinput when separating the minor acceptable risks from the major ones [4].

Risk analysis is performed throughout all the system life cycle phases. In the design phase,risk analysis can be used for two different purposes; as a design tool to specify requirements oras a control tool to control the risk level against an acceptance criteria. In the design phasesafety critical faults may be eliminated or their occurrence minimized, or the consequences of afault may be minimized thus reducing the risk [36]. In the operation phase of the system, riskanalysis can be used to analyse the effect of changes or to analyse causes of occured problemsand accidents.

Hazard analysis was originally applied in the safety domain, in which a system unintendedlycan enter an unsafe state. However, the intention behind a safety violation is immaterial, thusdeliberate malicious interference of humans, which is related to security, should also be includedin the hazard analysis [36].

The most common risk analysis methods used within system development are PHA (PreliminaryHazard Analysis), HazOp (Hazard and Operability Analysis), FTA (Fault Tree Analysis), andFME(C)A (Failure Modes, Effects (and Criticality) Analysis). Each of these are briefly describedbelow, and more detailed description can be found in [61, 46].

4.4.1 Preliminary Hazard Analysis (PHA)

PHA is used in the early design stage of a system in order to discover hazards early in thedevelopment process [55]. The aim is to identify safety design criteria and requirements, andthe identified hazards may be assessed in order to eliminate, reduce or control them. In theearliest stages of a development lifecycle, changes in the design will be made frequently. Thus,in order to be up to date on changes and new information on the design, the preliminary hazardanalysis needs to be an iterative process .

PHA identifies risks that are typical for the equipment or special activities. It does not considerthe effects and consequences of interactions in the system.

PHA consists of three steps:

1. Collection of information: Information about the system and information from previ-ous experiences with similar systems is obtained.

23

Page 38: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Risk Management

2. Excecution of the analysis: Hazards associated with the different elements of thesystem, possible (unwanted) consequences of the hazards, and design criteria and coun-termeasures used to eliminate or reduce the hazards are identified.

3. Documentation of results: The results from the analysis are documented in a PHAform that includes hazards, causes, consequences and countermeasures, and optionally aconsequence value to range the criticality of the hazards.

4.4.2 Hazard and Operability Analysis (HazOp)

HazOp is a bottom-up hazard identification technique. The purpose of a HazOp study is toidentify potential hazards and operability problems caused by deviations from design intent[55]. A HazOp team, consisting of a HazOp leader and 4-6 experts on (the relevant parts of)the system (domain experts), performs the HazOp study as a series of brainstorming meetings.At each study meeting a design representation is systematically examined using a series ofguidewords. Each guideword describes a specific type of deviation from design intent, and isused to focus the study and elicit ideas and discussion [56]. Each relevant guideword is appliedto each attribute so that the search for deviations is carried out in a structured manner. Whenall relevant guidewords have been applied to a given attribute, the other attributes of the entityunder consideration are examined in turn. Later, the rest of the entities are considered the sameway. In cases where a possible deviation is found when applying a guideword to an attribute,the study team investigates the causes and consequences as well as the protection or indicationmechanism of the deviation. Table 4.1, taken from the Defence Standard 00-58 [52], shows themost frequently used guidewords and common interpretations for PES (Programmable ElectronicSystems).

Guide word Example Interpretation for PES

No No data or control signal passed.

More More data is passed than intended.

Part of The data or control signals are incomplete.

Other than The data signals are complete but incorrect.

Early The signal arrives too early with reference to clock time.

Late The signal arrives too late with refernce to clock time.

Before The signal arrives earlier than intended within a sequence.

After The signal arrives later than intended within a sequence.

Table 4.1: Example guideword interpretations for PES [52].

4.4.3 Fault Tree Analysis (FTA)

FTA is primarily a means for analyzing causes of hazards, not for identifying hazards [46]. Anundesired system state is specified and the method works top-down to identify all its possiblecauses or combinations of causes. Ideally, all possible ways the undesirable event could occurshould be identified in the process.

As illustrated in Figure 4.2 the analysis is represented graphically as a tree structure with theundesirable system state as the the root node. The lower level causes are connected with eachother and the root node through a hierarchy of logical gates.

24

Page 39: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

4.5. RISK ESTIMATION AND RISK EVALUATION

Undesirable system state

Intermediate or pseudoevents

Basic or primary events

AND gate

OR gate

Figure 4.2: FTA fault tree

4.4.4 Failure Modes, Effects (and Criticality) Analysis (FME(C)A)

FMEA is a bottom-up approach for identifying hazards. The analysis identifies possible failuremodes of each component in the system, and determines the causes and consequences of thefailure modes. Furthermore, possible countermeasures are identified. If the seriousness, orcriticality, of the failure modes is ranked, the analysis is called a Failure Modes, Effects andCriticality Analysis (FMECA).

The four main steps of the FME(C)A are [36]:

1. Definition of the system, its function and components.

2. Identification of the component failure modes and their causes.

3. Study of the failure mode effects on the whole system as well as on the subsystem.

4. Conclusions and recommendations.

FME(C)A is normally carried out in the design stage of a system. The analysis is simple tocarry out, but it requires thorough knowledge of the system under consideration.

4.5 Risk Estimation and Risk Evaluation

Identified hazards must be associated with an estimated risk. A risk is defined as the consequencelevel of the hazard and the likelihood of the hazard to occur. The consequence values andlikelihood ranges used in this work are described in the Tables 4.2 and 4.3 respectively.

25

Page 40: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Risk Management

Table 4.2: Consequence values adapted from [51]Category DefinitionCatastrophic Death of personCritical Severe injury or severe occupational illness

Marginal Minor injury or minor occupational illness

Negligible No consequence for safety

Table 4.3: Likelihood ranges [51].Likelihood Occurrence during operational life considering all

instances of the systemFrequent Likely to be continually experienced

Probable Likely to occur often

Occasional Likely to occur several timesRemote Likely to occur some time

Improbable Unlikely, but may exceptionally occur

Incredible Extremely unlikely that the event will occur at all,given the assumptions recorded about the domainand the system

When the consequence and likelihood values of the hazard are estimated, the two values arecombined into an estimate of the level of risk. Table 4.5 shows the risk matrix used in this workfor assigning the hazards to a risk class, class I being the intolerable risks and class IV beingthe negligible risks (see table 4.4). Accepted risks are given the lowest priority and will not befurther evaluated, while not acceptable risks are assigned higher priority and must be treated.Because we in this work consentrate on safety consequences, risks that have no consequencesfor safety, and hence are assigned the consequence value negligible, are assigned to risk class IVindependent on the likelihood value.

Table 4.4: Risk Class Definitions [34]Risk class InterpretationClass I Intolerable risk

Class II Undesirable risk, and tolerable only if risk re-duction is impracticable or if the costs aregrossly disproportionate to the improvementgained

Class III Tolerable risk if the cost of risk reductionwould exceed the improvement gained

Class IV Negligible risk

Table 4.5: Risk Classification adapted from [34]Catastrophic Critical Marginal Negligible

Frequent I I I IVProbable I I II IV

Occasional I II III IVRemote II III III IV

Improbable III III IV IVIncredible IV IV IV IV

26

Page 41: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

4.6. TREAT RISK

4.6 Treat Risk

Ideally, all hazards in a system should be eliminated in order to make the system intrinsicallysafe. Unfortunately, total safety is not always possible to achieve. Hence, other techniques mustcomplement the principles of hazard elimination. The techniques are briefly described below.For a more detailed description, the reader is referred to [18].

Hazard elimination: Hazard elimination is the least expensive and the most effective way ofremoving hazards. Techniques for achieving this include substitution, simplification and reduc-tion of hazardous materials or conditions. One example of substitution is to use simple hardwareprotection mechanisms instead of a computer, which necessitates greater complexity, to enforcesafety constraints. Simplification applies to both software design and the use of a programminglanguage that encourages the production of simple and understandable programs. Reduction ofhazardous materials is achieved by only including code that is absolutely necessary to achievethe required functionality. Elimination of unused code has implications for the suitability ofusing COTS (Commercial off-the-shelf) in safety critical systems [46]. Additional functionalityand code may lead to hazards and make software hazard analysis more difficult. According toLeveson [46], reuse may decrease safety because of the complacency it engenders and becausethe specific hazards of the new system were not considered when the software was originallydesigned and constructed.

Hazard reduction: The next best alternative is to prevent or minimize the occurrence ofhazards, i.e. reduce the frequency with which the hazards are expected to occur. This canbe achieved by designing the system for controllability or through the use of barriers. Thefirst includes the use of feedback to allow corrective actions to be performed before significantdamage is done. The latter approach involves introducing a barrier between the hazards andthe potential victims. A barrier can prevent dangerous operations from being performed unlessit is safe (interlock barriers) or keep people away from dangerous parts of the system until it hasbecome safe (guard barriers). Interlocks use sensors to detect the state of the system in orderto detect dangerous conditions while guards use actuators to prevent exposure to danger. Anexample of guards is the use of automatic barriers on railway crossings. In cases where a barrieris identified to ensure safety, the barrier should be included in the safety requirements of thesystem.

Hazard control: The third option is to control the hazard if it occurs, i.e. reduce the likeli-hood of the hazard leading to an accident. This is achieved by using some form of automaticsafety devices [45]. Limiting exposure includes coding principles stating that critical flags andconditions should be written as close as possible to the code they protect. Furthermore, systemsshould always start out in a safe state. An example of isolation and containment is physicalbarriers such as concrete walls. An example of protection systems and fail-safe designs is awatchdog timer that times software to see if it appears to have gone dead.

Damage reduction: Damage minimization can take the form of warning devices, proceduresand training to help personnel react to hazards [45].

27

Page 42: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

28

Page 43: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Chapter 5

Wireless Networking

5.1 Introduction

The most conspicuous difference between wireless and wired networks is the transmission medium.In a wireless network, computers broadcast their information to one another by sending radiofrequency (RF) signals through the air. This differs from wired networks where electrical sig-nals are sent through wires. In addition to making networking easy, wireless networks makethe computers more portable as they are not wired up, but simply contains a wireless networkcard. With wireless networking, computers can communicate directly with every other com-puter on the network. This is called a peer-to-peer wireless network. Another alternative is aclient/server wireless network, which uses a wired controller access point to receive and forwardthe data between the wireless adapters installed on each computer.

A variety of access technologies for wireless computing have been deployed over the last fewyears. Mobile cellular communication systems and wireless networking technologies are grow-ing at an ever-faster rate, and this is likely to continue in the foreseeable future [26] . Thesecond generation (2G) cellular system GSM (Global System for Mobile Communications) isevolving into the third generation (3G) systems, such as UMTS (Universal Mobile Telecom-munications System) and cdma2000 (code-division multiple access), which provide worldwidecoverage. GPRS (General Packet Radio Service) (2.5G) has already been deployed to give IPconnectivity to GSM users. Other wireless solutions are also evolving. Wireless LANs, like IEEE802.11b, HIPERLAN and Bluetooth, have been deployed in hot spot areas to provide Internetaccess in e.g. hotels, airports and offices.

Communication on a shared medium can be intercepted by any of its users. Thus, anyonewith access to the medium can listen to or transmit data. Consequently, communication is nolonger private. In a shared medium, the presence of a communication request does not uniquelyidentify the originator, as it does in a single pair of wires per subscriber. In addition, all usersof the network can listen to any information that an originator sends to the network and canresend the information to place a fraudulent call. When the media are shared, privacy andauthentication are lost unless some method has been established to regain it. Cryptographyis a an example of a technology that provides the means to regain control over privacy andauthentication [25]. Further increases in network security are necessary before the promiseof mobile telecommunication can be fulfilled. Safety and security management against fraud,intrusions, and cloned mobile phones, will be one of the major issues in the next wireless andmobile generations [60].

29

Page 44: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Wireless Networking

5.2 Types of wireless systems

There are several wireless transmission systems, such as telecommunication systems, satellitesystems, broadcast systems, wireless LANs, wireless ATMs and infrared systems. WirelessLAN and infrared, which are the technologies used in this work, are described in the followingsubsections. Descriptions of the other technologies can be found in [57].

5.2.1 Infrared systems

Infrared systems communicates through transmission of infrared light. Infrared technology usesdiffuse light reflected at walls, furniture etc. or directed light if a line-of-sight (LOS) existbetween sender and receiver [57]. Advantages of infrared technology are that almost all mobiledevices have an infrared data association (IrDA) interface. Further, no licenses are needed fortransmission of infrared light. However, the bandwith of infrared transmission is very limited.Shielding is a property of infrared transmission which is regarded as both advantegous anddisadvantegous. The possibility to easily shield the transmission from its surroundings may begood in terms of confidentiality, but the reachability is limited as it cannot penetrate walls orother obstacles [57].

5.2.2 Wireless LAN

There are several technologies used by wireless LANs. Of the two basic transmission technologies,infrared and radio transmission, radio transmission is the most common. Radio transmissiontechnology transmits radiowaves in, for instance, the 2.4-GHz band. It can cover larger areasthan infrared transmission, and does not require a line-of-sight. Also, the transmission rateis higher. However, because shielding is hard with radio transmission, the transmission mayinterfere with other senders or the data transmitted may be destroyed by other electrical devices[57].

Wireless local area networks (WLANs) are typically restricted in their diameter to buildings, acampus, single rooms etc. and are operated by individuals, not by large-scale network providers[57]. Advantages of WLANs compared to wired LANs are, among other things, their flexibilityand robustness. With radiowaves as the transmission medium, senders and receivers can beplaced anywhere, as long as they stay within radio coverage, and in the case of disasters likeearthquakes or users pulling a plug, people can still communicate if the wireless device survives[57].

The devices used in a wireless LAN have to be equipped with a network interface card (NIC),which converts between the analog radio signals and the digital pulses used by computers. TheNIC typically includes one or more antennas and a radio transceiver [9].

5.2.2.1 IEEE 802.11b

The 802.11b standard, approved by the Institute of Electrical and Electronics Engineers (IEEE),is the most commonly followed standard for wireless LANs today. It uses the 2.4-GHz band fortransmission with a transmission speed of up to 11Mbit/s. The advantage of the 2.4GHz bandis that it represents an unlicensed frequency band reserved for industrial, scientific, and medicaluse on a global basis [29].

30

Page 45: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

5.3. SECURITY ISSUES IN WIRELESS LANS

The IEEE 802.11b wireless local area networking standard offers performance nearly compara-ble to that of Ethernet [9]. Because of the introduction of 802.11b (in September 1999), andthe continuing improvement in price vs. performance and reliability, the market for wirelesscommunications has grown, and is still growing, rapidly [9].

As shown in Figure 5.1, the 802.11b standard covers the MAC (Media Access Control) Layerand the physical layer of the OSI (Open System Interconnection) network model.

Application

Presentation

Physical

Data Link layer

Network

Transport

Session

Network protocols (TCP/IP, etc.)

IEEE 802.11b

802.2 Logical Link Control (LCC) 802.11 MAC header

802.11 PLCP header physical medium specs (RF, DSSS, etc.)

Figure 5.1: 802.11 and the OSI (Open System Interconnection) model [9]

5.3 Security issues in Wireless LANs

With a wireless LAN, transmitted data is broadcast over the air using radio waves or infraredlight. Radio waves cannot be controlled. They travel freely through most physical barriers,and hence the transmitted data may reach unintended receipents not only in the same room orbuilding as the transmitter, but also within a certain range outside the building. The free-spacewireless link is more susceptible to eavesdropping, fraud, and unauthorized transmission thanwired links. Unauthorized people can tap the radio signal from anywhere within range, or evenprevent other clients from transmitting by endlessly transmitting packets (i.e. a DoS attack).

However, wired networks are not more secure than wireless networks, they are just easier toprotect with physical barriers. To protect the data transmitted by radiowaves, we need tointroduce protection mechanisms at the physical or logical link layer instead of at the higherlayers, which is the case in traditional LAN networks. There are two mechanisms provided bythe IEEE 802.11b standard for providing access control and privacy on wireless LANs, namelyWired Equivalent Privacy (WEP) and Service Set Identifiers (SSIDs). For details about thesemechanisms, the reader is referred to [9].An alternative mechanism for ensuring privacy is to run a transparently Virtual Private Network(VPN) over the wireless LAN. VPN technology provides three levels of security: User authen-tication, encryption and data authentication. It provides the means to transmit data securelybetween two network devices over an unsecure data transport medium, and it offers a goodsolution for protecting data on a wireless network. A ”tunnel” is created on top of a protocolsuch as IP (Internet Protocol), and the traffic inside the tunnel is encrypted and totally isolated[9].

31

Page 46: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

32

Page 47: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Chapter 6

SONY AIBO

6.1 Introduction

“AIBO” is the name of the Sony entertainment robot, which is developed to encourage humanand robot interaction[21]. In Japanese, the word “aibou” means “partner” or “pal”, but thename is coined from a variety of other words as well, such as “A.I” (Artificial Intelligens), “eye”and “robot”. AIBO is different from traditional “worker robots”. AIBO is not helpful; it does

Figure 6.1: AIBO ERS-220A

not do your dishes or solve your math problems. What makes AIBO unique is its autonomy. Itcan both dance and sing, but it can also decide NOT to do something. Moreover, AIBO com-municates emotions, such as happiness, sadness, anger, surprise, fear and dislike. AIBOs way ofcommunicating its emotions is through combinations of musical tones, eye light colors and bodylanguage. AIBO can actually “learn” and mature through developmental stages such as toddlerphase, child phase, adolescent phase and adult phase. It learns based on experience and envi-ronment, as it responds to sounds and patting, and then “instinctively” wants to communicatewith the user. AIBO have four instincts; love instinct, search instinct, movement instinct andrecharge (eating) instinct.

6.2 Communication

Using a wireless card, AIBO can communicate with a PC. This PC also needs to be equippedwith a wireless LAN card, unless it is connected to a wired LAN network with a wireless LANaccess point. Figure 9.36 shows possible network configuration for communication over wirelessLAN.

33

Page 48: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

SONY AIBO

Figure 6.2: Wireless LAN network configurations [20].

There are four possible types of wireless LAN network configurations: Communication throughan access point from a wireless LAN-enabled PC, communication through an access point froma PC connected to the wired LAN network, and two variations of communication with a wirelessLAN-enabled PC without the use of an access point. For details about the configurations andsettings, the reader is referred to [20].

The AIBO Wireless LAN Card ERA-201D1 for AIBO ERS-210 conforms to IEEE802.11b anduses TCP/IP for communication [20]. In IEEE802.11b wireless LAN standard, the 2.4-GHzband is divided into 14 channels. To prevent a radio frequency interference, separate channelscan be specified for different wireless networks that are close to each other. The AIBO WirelessLAN Card ERA-201D1 can use channels 1 to 11. In infrastructure mode, a channel specifiedby the access point is used by all the devices within the network. In ad hoc mode, the channelmust be specified by all the devices within the network [20].

6.3 Programming AIBO

The software of AIBO resides on a removable Memory Stick. Commercial off-the-shelf softwareis available, but it is also possible to develop your own programs. The AIBO used in this workis programmed using OPEN-R, which is briefly described below. An alternative tool for makingprograms for AIBO is the AIBO Master Studio.

6.3.1 OPEN-R

OPEN-R, or the Open architecture for Robot entertainment, is a standard for entertainmentrobot software and robot parts, and the interface that Sony is promoting for the entertainmentrobot systems to expand their capabilities [19]. The software platform of the Open-R is based onApertos [68], a fully object-oriented real-time distributed operating system developed by Sony.

34

Page 49: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

6.3. PROGRAMMING AIBO

This allows each physical and software component to be defined uniformly as a distributedobject.

OPEN-R software is object-oriented and modular. Software modules are called ”objects”, andthe programming model allows concurrently running objects to communicate with each other.Each object is loaded from a ”Memory Stick”. Further, an object is a concept that only existsat run-time. Each object corresponds to one executable file created at compile-time. Theexecutable file usually has the extension of ”.bin”. Source code is compiled and linked to createthis executable file. Then, the file is put on an AIBO Programming Memory Stick. WhenAIBO boots, the system software loads the file from the AIBO Programming Memory Stick andexecutes it as an object. Each object has its own thread of execution and runs concurrentlywith other objects in the system.

To program AIBO using OPEN-R, the OPEN-R SDK development environment is providedfree of charge [53]. The OPEN-R SDK is a low-level, compiled API based on gcc (C++) wheresoftware that works on AIBO (ERS-210, ERS-220, ERS-210A, and ERS-220A) can be made.The APIs are written in C++, and are for the most part very similar to a UNIX environment,except for process control and inter-process communication. The development environmentuses a patched version of the 2.9.5 GCC compiler, and can be run on almost any UNIX basedplatform, including Mac OS X and cygwin under Windows. With the OPEN-R SDK AIBO’sfunctions can be utilized, such as making AIBO’s joints move, get information from sensors,get image from camera and use wireless LAN (TCP/IP). However, the actual source code usedinside AIBO is not disclosed by Sony because of commercial business reasons.

OPEN-R supports networking over wireless LAN and a TCP/IP network protocol. To runOPEN-R programs, an AIBO Programming Memory Stick (ERA-MS008), and AIBO Entertain-ment Robot (ERS-210, ERS-220, ERS-210A, or ERS-220A), an AIBO Wireless LAN card (ERA-201D1), and an IEEE802.11b compliant Wireless LAN card for your PC (or an IEEE802.11bcompliant Access Point connected to your LAN) is needed.

To use the OPEN-R SDK the following tools are needed:1. General UNIX like commands (sh, cp, etc..)2. perl3. GNU make4. GNU binutils, gcc, and newlib that are built for MIPS cross-compilation.All tools are compatible with normal UNIX environment.

35

Page 50: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

36

Page 51: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Chapter 7

LEGO Mindstorms

7.1 Introduction

LEGO Mindstorms is the result of a collaboration between LEGOr and the MassachusettsInstitute of Technology (MIT). The work, which started in 1986, lead to the development of aprogrammable brick, a small unit capable of connecting to the external world through a varietyof sensors and actuators [23]. Adding these computerized bricks, motors and sensors to thetraditional plastic bricks made it possible to design LEGO robots that could interact with thesurroundings.

The LEGO Mindstorms Robotics Invention System (RIS) has been available for commercial usesince 1998. It contains all the parts necessary to build and verify the basic design of almost anymechanical invention [5]. Hence, LEGO Mindstorms can play an important role in prototyping.

7.2 Components of LEGO Mindstorms

The main elements of LEGO Mindstorms are the RCX Brick, the motors and sensors, and theIR tower. These are briefly described in the following sections. For more detailed descriptionsof these and other elements of the RIS kit, the reader is referred to [7, 5, 23]

7.2.1 RCX Brick: The Robotics Command eXplorer

The Robotic Command eXplorer (RCX) brick (see Figure 7.1) is the kernel of any Mindstormsrobot and is capable of interacting with the physical world through sensors and motors. The RCXbrick encloses a tiny computer based on a Hitachi H8 series microcontroller. The microcontrollerchip also contains 16 kB of ROM and 32 kB of RAM, 3 input ports that can accept a variety ofLEGO sensors, three output ports used to control actuators (controllable devices), one infraredport and one speaker, as well as circuitry to provide for limited user interaction. The latterconsists of an LCD, which can be used to indicate the internal state of the RCX brick, and fourbuttons; On-Off, Run, Prgm and View. The RCX is powered by six AA batteries.

7.2.2 Motors

Motors represent the actuators in LEGO Mindstorms and can be attached to the output portsof the RCX. Two 9-volt motors are included in the RIS kit. The power level of the motors range

37

Page 52: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

LEGO Mindstorms

LCD display

IR port

Sensor inputs

RUN button

Motor outputs

Figure 7.1: The LEGO Mindstorms RCX

from 0 to 7. By decreasing the power to a motor the output gets weaker. Actuators are used torespond to stimuli. In most cases the stimulus is obtained from the environment via sensors.

7.2.3 Sensors

Sensors are used to obtain stimuli from the environment and are the only link to the outsideworld. The stimuli are sent to the RCX through the RCX’s input ports, to which the sensorsneed to be attached. The RCX can process stimuli data in order to determine an appropriateaction.

The LEGO Mindstorms kit comes with a core set of four sensors, including a light sensor, atouch sensor, a rotation sensor and a temperature sensor. In addition to these, different manu-facturers have developed additional sensors that can be combined with LEGO. Examples are thedistance sensor, the reflective obstacle detector and the passive and active sensor multiplexerfrom Mindsensors [48], and the infrared emitter/detector from HiTechnic [30].

7.2.4 IR Transmitter tower

Instead of cabling, an IR tower (see Figure 7.2) is used to download programs to the RCX andfor the communication between the RCX and the PC. The data is transmitted through infraredports on the IR tower and on the RCX brick. Even when a program is running on the RCX,data can be transmitted to it through the IR tower as commands from the PC or from anotherRCX brick.

Depending on the version, the RIS kit comes with either a serial port tower (in RIS 1.0 and1.5) or a USB tower (in RIS 2.0). The advantage of the USB tower is that it does not requirebatteries. However, a disadvantage with the USB tower is that the Java Communications APIis not compatible with USB ports. How to overcome this problem is described in detail in [23].

38

Page 53: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

7.3. COMMUNICATION

Figure 7.2: LEGO Mindstorms IR Tower

7.3 Communication

The memory of the RCX brick is limited. However, the ability to communicate between the RCXbrick and a PC makes it possible to expand the complexity of a robotic system. To transmitdata, there must be a program running on the RCX as well as a separate program running on thePC [7]. Complex and memory-intensive code can be residing in the PC, and the PC can controlthe behavior of the RCX. Data in the RCX can also be sent back to the PC to be analyzed. Inaddition, communication between two RCX bricks is possible, which allows multiple RCXs tocooperate to accomplish a joint mission [7].

The IR tower can only receive data while the green LED is on, which is only when the PC sendsdata. Thus, the PC must initiate all data transfer [5]. A problem with this is that a signal canbe lost if the PC and the RCX send signals at the exact same time.

7.4 Programming with LEGO Mindstorms

Several programming languages are available for the RCX. BrickOS is used for the prototypedeveloped in this work, and is hence briefly described below. Other possible languages are lejOS,NQC, pbFORTH and Visual Basic, which are briefly described in [5].

7.4.1 BrickOS (LegOS)

BrickOSTM [12] is the new name for legOS (the first open-source operating system for LEGOMindstorms robots). BrickOS provides a C/C++ development environment for RCX programs.It uses gcc and g++ (the GNU C and C++ cross compiler tool chain) and the necessary toolsto download programs to the RCX.

As shown in Figure 7.3, the brickOS program is compiled on the host computer. This gener-ates binary code that can be downloaded to and executed natively on the RCX. The brickOSoperating system executes the program and provides an interface to the RCX’s hardware.

The library functions of the brickOS provide access to the various features of the RCX andthe OS [8]. These functions are related to three main categories; outputs, inputs and programcontrol. The output functions provide for interaction to the outside world through motors and

39

Page 54: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

LEGO Mindstorms

C Compiler

Hardware

System ROM

brickOS

User Programs

Native Binary Code Host Computer

RCX

brickOS Program

Figure 7.3: RCX Architecture with brickOS [8]

the LCD on the RCX brick. The input functions allow a program to get data and extractmeaning from the outside world and from the user through sensors and the buttons on the RCXbrick. For program control brickOS support sleep functions, threading and semaphores amongother things.

40

Page 55: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Chapter 8

Development Process

8.1 Introduction

Lifecycle models are useful means of describing the various phases of a development project,from the conception of a system to its eventual decommissioning [61]. Several standards existto guide the development of safety critical systems, e.g. IEC 61508 [33] and the MIL-STD-882Bstandard [36]. The Australian/New Zealand standard AS/NZS 4360:1999 Risk management [4]specifies the elements of the risk management process.

In this chapter we will describe the development process proposed for the security-safety criticalsystem. As this system is regarded both safety and security critical, a development processintegrating both security and safety aspects is specified. The process is based on the safetylifecycle from the IEC 61508 standard [33] and the CORAS integrated risk management andsystem development process [11]. These development processes will be further described in thefollowing sections. The resulting security-safety lifecycle is presented in Section 8.4.

8.2 IEC 61508

The IEC standard IEC 61508 (Functional safety of electrical/electronic/ programmable elec-tronic safety-related systems) [33] covers important aspects that need to be addressed whenelectrical, electronic, and programmable devices are used in connection with safety functions.The strategy of the standard is to derive safety requirements from a hazard and risk analysis andto design the system to meet those safety requirements, taking all possible causes of failure intoaccount. The essence is that all activities relating to functional safety are managed in a plannedand methodical way, with each phase having defined inputs and outputs [13]. The standardconsiders all phases in a safety lifecycle, from initial concept, through design, implementation,operation and maintenance to decommisioning. Figure 8.1 illustrates the IEC 61508 process,which is further described in the reminder of this section.

The process consists of the following phases:

1. Concept: An understanding of the system and its environment is developed.

2. Overall scope definition: The boundaries of the system and its environment are deter-mined, and the scope of the hazard and risk analysis is specified.

41

Page 56: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Development Process

Overall operation and maintenance

planning

6 Overall

installation and commissioning

planning

8 Overall safety

validation planning

7

Overall planning

Concept 1

Overall safety requirements 4

Safety requirements allocation 5

Hazard and risk analysis 3

Overall scope definition 2

Safety-related systems: E/E/PES

9

Realisation (see E/E/PES

safety lifecycle)

Overall modification and retrofit 15

Decommissioning or disposal 16

Overall operation, maintenance and repair 14

Overall installation and commissioning 12

Overall safety validation 13

Back to appropriate overall safety lifecycle

phase

Safety-related systems:

other technologiy

10

Realisation

External risk reduction facilities

11

Realisation

Figure 8.1: Overall safety lifecycle, IEC 61508 [33]

3. Hazard and risk analysis: Hazards and hazardous events of the system, the eventsequences leading to the hazardous events, and the risks associated with the hazardousevents are determined.

4. Overall safety requirements: The specification for the overall safety requirements isdeveloped in order to achieve the required functional safety.

5. Safety requirements allocation: The safety functions contained in the overall safetyrequirements specification are allocated to the safety-related system, and a safety integritylevel is allocated to each safety function.

6. Overall operation and maintenance planning: A plan is developed for operating andmaintaining the system, and the required functional safety is ensured to be maintainedduring operation and maintenance.

7. Overall safety validation planning: A plan for the overall safety validation of thesystem is developed.

8. Overall installation and commisioning planning: Plans, ensuring that the requiredfunctional safety are achieved, are developed for the installation and commissioning of the

42

Page 57: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

8.3. CORAS MODEL BASED RISK ASSESSMENT

system.

9. Safety-related systems: E/E/PES: The E/E/PES safety-related system is createdconforming to the safety requirements specification.

10. Safety-related systems: other technology: Other technology safety-related systemsare created to meet the requirements specified for such systems (outside scope of thestandard).

11. External risk reduction facilities: External risk reduction facilities are created to meetthe requirements specified for such facilities (outside scope of the standard).

12. Overall installation and commisioning: The E/E/PES safety-related system is in-stalled and commisioned.

13. Overall safety validation: The E/E/PES safety-related system is validated to meet theoverall safety requirements specification.

14. Overall operation, maintenance and repair: The system is operated, maintainedand repaired in order to ensure that the required functional safety is maintained.

15. Overall modification and retrofit: The functional safety of the system is ensured tobe appropriate both during and after modification and retrofit.

16. Decommisioning or disposal: The functional safety of the system is ensured to beappropriate during and after decommisioning or disposing of the system.

8.3 CORAS model based risk assessment

The EU-funded CORAS project (IST-2000-25031) [17] has developed a framework for model-based risk assessment of security-critical systems [11]. The CORAS framework is founded onfour pillars, as shown in Figure 8.2. The risk management process and the integrated risk man-agement and system development process will be briefly described in the following subsections,as they are relevant for our development of the development process for security-safety criticalsystems. A description of the risk documentation framework and the platform for tool inclusionbased on data-integration can be found in [11].

43

Page 58: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Development Process

Model-based Model-based risk assessment risk assessment

methodology methodology

XML

UP

Integrated risk management and

system development

process

Platform for tool inclusion based on data-integration

Risk management

process

AS/NZS 4360 RM-ODP

Risk documentation

framework

Figure 8.2: The CORAS framework [11]

The main focus of this framework is model-based risk assessment, which differs from traditionalrisk assessment in the sense that it [11]:

- combines complementary risk assessment methods for assessing different models of thetarget of evaluation;

- gives detailed recommendations for the use of modelling methodology in conjunction withrisk assessment;

- provides modelling methodology to support the documentation of risk assessment results.

The motivation for developing a model-based risk assessment methodology is compound. [11]mentions several hypothesis which favours a model-based risk assessment. Examples of hypoth-esis are:

- A modelling methodology leads to more precise and correct descriptions of the target ofevaluation, its context and security issues. This is likely to improve the quality of the riskassessment results.

- A modelling methodology provides a basis for tighter integration of risk management inthe system development process, which may reduce development costs and ensure that thespecified level of security is achieved.

- A modelling methodology facilitates communication and interaction during the risk as-sessment because of the graphical style of UML.

8.3.1 The risk management process

The CORAS risk management process is based on AS/NZS 4360:1999 Risk Management [4] (seeChapter 4.3) and ISO/IEC 17799:2000 Code of Practice for Information Security Management

44

Page 59: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

8.3. CORAS MODEL BASED RISK ASSESSMENT

[39], and complemented by ISO/IEC 13335:2001 Guidelines for the management of IT-Security[38] and IEC 61508: Functional Safety of Electrical/Electronic/Programmable Electronic SafetyRelated Systems [34].

The risk management process in the standard AS/NZS 4360:1999, described in Chapter 4.3,is a generic framework. As CORAS addresses security-critical systems in particular, they havespecified a refinement of the process aiming at the security domain. The activites of the CORASrisk management process are specified in Table 8.1.

Table 8.1: Activities of the CORAS risk management process [31]Sub-process 1: Identify Context Sub-process 4: Risk Evaluation

Activity 1.1: Identify areas of relevance Activity 4.1: Determine level of risk

Activity 1.2: Identify and value assets Activity 4.2: Prioritise risks

Activity 1.3: Identify policies and evaluation criteria Activity 4.3: Categorise risks

Activity 1.4: Approval Activity 4.4: Determine interrelationships among riskthemes

Sub-process 2: Identify Risks Activity 4.5: Prioritise the resulting risk themes andrisks

Activity 2.1: Identify threats to assets

Activity 2.2: Identify vulnerabilities of assets Sub-process 5: Risk Treatment

Activity 2.3: Document unwanted incidents Activity 5.1: Identify treatment options

Activity 5.2: Assess alternative treatment approaches

Sub-process 3: Analyse Risks

Activity 3.1: Consequence evaluation

Activity 3.2: Frequency evaluation

8.3.2 The integrated risk management and system development process

The CORAS system development process is an adaptation of UP (Unified Process), and inanalogy to RUP, the CORAS process is both stepwise incremental and iterative [22]. Each phaseof the system lifecycle, including inception, elaboration, construction and transition, includesconstruction of increasingly detailed models of the system [11].

The integrated risk management and system development process is based on the integration ofthe risk management process into the UP, as shown in Figure 8.3. As more information is incor-porated in the context of the analysis there is always the potential that new vulnerabilities areidentified [22]. This must be taken into account during the risk analysis of the composite entity,hence subsequent iterations are performed before progressing to the next phase. Consequentlythe risk management process follows the iterations of the development lifecycle.

45

Page 60: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Development Process

MANAGE RISK

iterate

review risks and consult

Choose a part

Architect a part

Analyse a part

Compose in

I n c e

p t i o

n

iterate

review risks and consult

Choose a part

Architect a part

Analyse a part

Compose in

E l a

b o r

a t i o

n

iterate

review risks and consult

Choose a part

Architect a part

Analyse a part

Compose in

C o

n s t

r u c t

i o n

iterate

review risks and consult

Choose a part

Architect a part

Analyse a part

Compose in

T r a

n s i

t i o n

Monitor and review

Identify Context

Treat Risk Risk Evaluation

Analyse Risks Identify Risks

Communicate and consult

Figure 8.3: Part of the integrated risk management and system development process [11]

8.4 Security-Safety Lifecycle

The system presented in this report is both safety and security critical and we want to assessboth the safety and security aspects of the system. Inspired by the safety lifecycle of the IEC61508 standard and the CORAS integrated risk management and system development processfor security critical systems, we have specified a proposal for a development lifecycle process forsecurity-safety critical systems. The process is both stepwise iterative and incremental. For eachiteration phase more information is added and increasingly detailed versions of the system areconstructed through subsequent iterations. The integrated risk management process is appliedin all phases, and iterates itself within each phase. The resulting “security-safety lifecycle” isdepicted in Figure 8.4.

In the first two steps, the concept and overall scope definition of the system is defined. Asystem description and a functional requirements proposition are the results of these steps, andare used as input to the next step; the preliminary hazard analysis (PHA). By performing aPHA early in the development process, the most obvious and conspicuous potential hazards canbe identified and handled more easily and at a lower cost. Furthermore, the PHA aids in theelicitation of safety requirements for the system, which is the fourth step in the developmentprocess. Based on the safety requirements, and the security-safety or security policy if oneexists for the organisation, security requirements are specified. Step 4.3 is identification ofsecurity threats. A possible approach, and the one used in this work, is to use a modifiedHazOp method, specifically suited for identifying security threats. This modified HazOp, called“security-HazOp”, is further described in Chapter 9.5.1. Identified security threats are used asinput to the risk analysis step. In risk analysis, safety consequences of the security threats areidentified. The safety consequences are assigned a consequence value and a likelihood value inorder to estimate the level of risk. Based on the risk estimation, the risks are evaluated andeither accepted or not accepted. Not acceptable risks are treated by introducing safeguards, and

46

Page 61: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

8.4. SECURITY-SAFETY LIFECYCLE

the risk management step is iterated until no unacceptable risks remain. The system can thenbe designed, and ideally the risk management step is repeated with the design specification asinput. When the required safety level of the system is achieved for the proposed design, thesystem is implemented and tested. If the implemented version is not approved, the process isagain reiterated from the risk management step. The whole process is reiterated from the topwhen updating the system description and requirements with more information and detail.

Due to the fact that this work only considers the development process, not the whole lifecycle ofthe system, the last three phases of the safety lifecycle of IEC 61508, covering system operation,maintenance and decommisioning, are not included.

Risk Management

Implementation 6

Testing and Safety validation 7

Concept 1

Overall Scope Definition 2

4

Preliminary Hazard Analysis 3

Design 5

Security requirements

4.2 Identify security threats

4.3

Evaluate Risk

4.5 Treat Risk

4.6

Safety requirements

4.1

Accept Risk

Analyse Risk 4.4

Identify safety

consequences 4.4.1

Identify likelihood

4.4.2

Estimate level of risk 4.4.3

No

Yes

I t e

r a t e

( m

o r e

i n f o

r m a

t i o n

/ d e

t a i l )

I t e r

a t e

Update system description and requirements

4.7

Figure 8.4: Security-safety lifecycle

47

Page 62: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Development Process

Table 8.2: Steps of the security-safety lifecycleStep Description Chapter1. Concept The intention and the objective of developing the sys-

tem are established9.2

2. Overall Scope Definition A system description and functional requirements aredeveloped

9.2

3. Preliminary Hazard Analysis The system description and functional requirementsfrom the previous step are used as input to the pre-liminary hazard analysis (PHA). The PHA is carriedout at this early stage in order to identify and elude themost obvious and conspicuous potential hazards of thesystem

9.3

4. Risk Management4.1 Safety requirements The results of the PHA provides input to the identi-

fication of safety requirements of the system. Safetyrequirements specifies what the system must and mustnot do in order to ensure safety

9.4.2

4.2 Security requirements Based on the safety requirements, and the security-safety or security policy if one exists for the organisa-tion, the security requirements for the system are spec-ified. Security requirements are needed to ensure theconfidentiality, integrity, authenticity, availability, relia-bility, accountability and non-repudiation of the system

9.4.2

4.3 Identify security threats Identification of vulnerabilities associated with the se-curity requirements may uncover security threats

9.5

4.4 Analyse Risk 9.64.4.1 Identify safety consequences The security threats revealed may result in conse-

quences for the safety of the system. In this stage, thesecurity threats are assigned a safety consequence value

9.6.1

4.4.2 Identify likelihood The likelihood of the safety consequences needs to beidentified in order to evaluate the risk in the next step

9.6.2

4.4.3 Estimate level of risk Based on a combination of the consequence and likeli-hood values the level of risk is estimated,and the safetyconsequence is assigned to a risk class

9.6.3

4.5 Evaluate Risk The risk of the safety consequences are evaluated. Secu-rity threats leading to unacceptable safety consequencesmust be treated

9.7

4.6 Treat Risk If the safety consequences are unacceptable in light ofthe adequate safety level of the system, safeguards areintroduced, and the risk management process iteratesuntil the safety of the system is acceptable. New safetyrequirements may arise from the safeguards introduced,which may again give rise to new security requirementsand so on

9.8

4.7 Update system description When introducing new safeguards the system descrip-tion and

9.8.1

and requirements requirements specification must be updated5. Design When no more unacceptable risks are identified, the sys-

tem is designed. Before approaching to the implementa-tion step, the risk management step should be repeated

9.9

6. Implemention When the design is approved, the system can be imple-mented, and ideally the risk management step repeatedagain

9.10

7. Testing and Safety validation After implementing the system, it has to be tested inorder to assure that all security requirements and safetyrequirements are fulfilled

9.11

48

Page 63: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Chapter 9

Security-Safety Critical System

9.1 Introduction

A security-safety critical system is a system where a security critical system monitors and con-trols a safety critical system.

In this chapter we illustrate the development process for security-safety critical systems proposedin the previous chapter using a simple prototype system. The process is illustrated in Figure8.4. Each step of the security-safety lifecycle is described in Table 8.2, where the last columnindicates in which section of this chapter the corresponding step is described. The first twosteps are described in Section 9.2. The system description is contained in this section, but inorder to keep all requirements in one requirements specification, the functional requirementsresulting from these steps are presented together with the safety and security requirements (ornon-functional requirements) in Section 9.4. Section 9.3 presents the preliminary hazard analysis(PHA), while the sub activities of the risk management step are presented in Sections 9.4-9.8.If new safeguards needs to be introduced in step 4.6 Treat Risk, the system description andrequirements specification must be updated. Thus, Section 9.2 and 9.4 contain both first andupdated versions. The three last steps in the lifecycle, design, implementation and testing andsafety validation, are discussed in Sections 9.9, 9.10 and 9.11, respectively.

9.2 Concept and Overall Scope Definition

Concept and overall scope definition constitute the first two steps of the security-safety devel-opment process specified in Chapter 8 (see Figure 9.1). The main objective of this thesis is tolook into these two domains in order to clarify similarities and differences, and most importantlydependencies between the security and the safety of a system. The main scope for the studyis to concretize how the two terms interact and to propose a development process for systemswhere both factors are present. This is conducted by performing risk analysis on a prototype ofa security-safety critical system, and then study the results combined with existing backgroundinformation in the fields of safety and security.

49

Page 64: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

Implementation 6

Testing and Safety validation 7

Concept 1

Overall Scope Definintion 2

Preliminary Hazard Analysis 3

Design 5

I t e r

a t e

( m

o r e

i n f o

r m a

t i o n

/ d e

t a i l )

I t e r a

t e

Risk Management 4

Figure 9.1: Concept and Overall Scope Definition

To be security-safety critical the system must include a security critical part and a safety criticalpart. An example architecture of such a system is presented in Figure 9.2. As indicated inthe figure the security critical part can be represented by a control system used to protectthe safety critical part of the system. The control system might include a monitoring systemand a protection system. The monitoring system is dependent on sensors that monitors thesafety critical system. Based on information from the monitoring system, the protection systemprotects the safety critical system by using protection mechanisms (actuators).

Security-Safety Critical System

Monitoring system

Protection system

Sensors

Control System

Actuators

Security Critical System

Safety Critical System

protects

Figure 9.2: Example architecture of a security-safety critical system

A real world area of application could be a tunneling system where vehicles over a fixed size arenot allowed to drive through because of safety reasons. The tunnel represents the safety criticalpart, while a surveillance camera and a gate with a controller, represent the control system. At-tacks on the control system, whether malicious or nonmalicous, together with technical failures,represent a threat to the safety, as they may result in oversized vehicles entering the tunnel. Inorder to close the gate when oversized vehicles approach while at the same time letting other

50

Page 65: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.2. CONCEPT AND OVERALL SCOPE DEFINITION

vehicles pass, the control system must be able to distinguish between the vehicles. This can beaccomplished through e.g image processing.

9.2.1 System description

This section describes the prototype developed in this thesis. As the system is used as a meansin the study of safety consequences of security threats, only a simple prototype is developed.The system is presented in Figure 9.3. As shown in the figure, the system is a prototype ofa robot production cell1, which will be denoted as the factory. The industrial robot in thefactory is represented by a LEGO Mindstorms cutting robot. While operating, the cuttingrobot represents a threat to anyone approaching it. Since the cutting robot can cause harmto life, property or environment it is regarded as safety critical and placed inside a safety zoneenclosed by walls.

Safety zone

Cutting robot

On/Off buttons

Yellow/ red light

Sony AIBO ERS-220

Laptop with wireless Lan card

Wireless LAN

Gate

Gate wheel

Infra red

IR tower RCX

Factory

Entrance area

C a b l e

Figure 9.3: The security-safety critical system

The safety zone must be protected in order to prevent humans from approaching the industryrobot while it is working. However, it must be possible to enter the safety zone for maintenancework. Thus, when someone enters the zone, a control system is responsible for stopping theindustry robot. Only authorized staff should be allowed to enter the safety zone to performmaintenance work. People not trained for operating in the safety zone are more likely to be

1A robot production cell is a closed area where one or more industrial robots work together.

51

Page 66: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

injured. Hence, the control system should be able to distinguish between authorized and unau-thorized staff. To prevent unauthorized persons, whom will be call “intruders”, from enteringthe safety zone, a LEGO Mindstorms gate, used to represent the protection system, is placed infront of the entrance to the zone. If an intruder approaches the entrance, the gate will be closed.The monitoring system is represented by a Sony AIBO robot. The robot is used to monitorthe area in front of the entrance into the safety zone; the entrance area. If the AIBO detectsan intruder, it notifies the PC controller, which again notifies the LEGO system who closes thegate. If the AIBO detects someone entering the safety zone, the PC and LEGO system arenotified, and the LEGO system stops the cutting robot.

The cutting robot can be started and stopped manually by pressing the On and Off buttons inthe entrance area, or remotely through a control window on the PC controller. A yellow lightoutside the safety zone indicates that the cutting robot is working, a red light indicates that thegate is closed.

As AIBO can distinguish between colours, authorized and unauthorized staff are represented bydifferent colours in the prototype system. A green LEGO man represents an authorized personwhile a pink ball represents an intruder. When AIBO detects the pink ball inside the entrancearea, it notifies the PC controller via the wireless LAN. The PC controller then sends infraredsignals to the LEGO system ordering it to close the gate. When the intruder retreats from theentrance area, AIBO will lose track of him, and hence notify the PC controller that the intruderhas left the area. The PC controller then orders the LEGO system to reopen the gate. WhenAIBO detects the green LEGO man in the entrance area, it does nothing. If AIBO detects thata person (either auhtorized or unauthorized) enters the safety zone, it notifies the PC controllerin order to stop the cutting robot.

The prototype assumes that only one person can enter the entrance area simultaneously dueto restrictions in the equipment and time limitations, as well as the sample program of whichthe AIBO program is built. As soon as AIBO detects a green man (or a pink ball), it followsit by rotating its head. As long as AIBO is following the green man (or the pink ball) it cannot detect anything else. A suggestion for further work would be to implement a mechanism forkeeping count of more than one person at a time. Another suggestion for further work wouldbe to implement e.g. face recognition to distinguish between authorized and unauthorized staff.

The safety critical part of our prototype was chosen to be a LEGO Mindstorms robot, basedon already acquired knowledge of LEGO Mindstorms through the project “Risk Assessment ofSafety Critical Systems: An approach using LEGO Mindstorms for prototyping” [28]. For thesecurity critical control system, a Sony AIBO robot was decided to represent the monitoringsystem, whereas the protection system was chosen to be represented using a LEGO Mindstormsgate. To link the AIBO and the gate, the control system also includes a PC. The PC controlleris responsible for interpreting the messages from the monitoring system and, based on thesemessages, performing the required actions to ensure the safety of the system. The PC controllercarries out its responsibilities by initiating actions in the protection system or in the industrialrobot. The control system is regarded as security critical as its components may contain vul-nerabilities that can be exploited. These security threats can then lead to consequences for thesafety of the system.

Both the safety critical robot and the protection gate are built using LEGO Mindstorms andthe same LEGO RCX have been used for both assets. Hence, as shown in Figure 9.4, the LEGOsystem is overlapping the safety and security critical systems as it contains assets from both.

The PC controller communicates with the AIBO through wireless LAN and with the LEGOsystem through infrared (IR) signals. Hence, the PC controller is equipped with a wireless LAN

52

Page 67: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.2. CONCEPT AND OVERALL SCOPE DEFINITION

Security-Safety critical system: FACTORY

Security critical control system

Monitoring system: AIBO

PC controller

Safety critical system

LEGO system

Cutting robot Protection system:

Gate RCX

Figure 9.4: Components of the Security-Safety critical system

card and an IR tower. Together the AIBO, PC controller, RCX, gate and communication links(WLAN and IR) make up the control system and constitute the security critical part of thesystem.

9.2.2 Updated system description after PHA and Security-HazOP

In this section we focus on updates to the system description after the PHA and risk managementsteps of the development cycle. The PHA and risk management will be described in the followingsections.

The safety zone is not safe to enter while the cutting robot is operating. Hence, to increase thesafety, the gate confining the safety zone should be closed whenever the cutting robot is working.However, it should still be allowed to enter the safety zone for maintenance work. In order tomeet this demand we respecified the system so that the gate is closed until AIBO detects anauthorized person in the entrance area. If it detects an intruder, the gate remains closed. Sincethe gate should never be open when the cutting robot is working, the cutting robot must bestopped before the gate can be opened. This could have been solved by both opening the gateand stopping the cutting robot when AIBO detects an authorized person. However, it wouldhave a negative effect on the productivity of the factory as people may enter the entrance areafor other reasons than entering the safety zone. Further, there should be possible to open andclose the gate manually in case the system becomes unavailable. For these reasons, the gatewere extended with a lock, so that the gate could be either (1) open, (2) closed and locked, or(3) closed but unlocked. Further, a wheel were attached to the gate in order to allow the gateto be opened when unlocked.

If AIBO detects a green man (representing authorized staff), it notifies the PC controller, whichnotifies the LEGO system in order to unlock the gate. As long as the authorized person stayswithin the entrance area, the gate is unlocked. When the gate is unlocked it can be opened byturning a wheel in the entrance area, and doing so will automatically stop the cutting robot ifit is working. When the gate is open, it can be closed by pressing the On button outside thesafety zone. The On button has to be pressed twice for the cutting robot to start working again;one time for closing the gate, and one time for starting the robot. When the authorized personleaves the entrance area and returns to the factory, the gate is closed (if the authorized persondid not close it manually) and locked.

If AIBO detects a pink ball (representing an intruder) in the entrance area no actions need tobe taken since the gate is already closed and locked. However, AIBO will still notify the PC

53

Page 68: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

controller, and a message stating that an intruder is observed in the entrance area (where heshould not be) is displayed in the control window so that the “security guard” is informed aboutthe violation of the intruder.

Only authorized staff are allowed to start and stop the cutting robot. For safety reasons,however, the Off button in the entrance area works as a “panic button”, and must be accessiblefor unauthorized as well as authorized people. This is implemented by enabling the On buttonwhen an authorized person is observed in the entrance area. Further, the PC controller needsto be protected using an access control mechanism such that only authorized staff is allowed tocontrol the factory from the control window. The Windows login included in Windows XP ofthe PC controller is considered sufficient for the purpose of the prototype. To prevent anyonefrom starting the cutting robot while someone is inside the safety zone, it is not possible to startthe cutting robot neither remotely from the PC controller nor manually by the On button inthe entrance area if the gate is open.

Transferring the new specification to the tunneling system described earlier in this chapter, weget the principle of a toll bar. However, instead of payment, the “admission ticket” is a legalsized vehicle. With the old design a failure in the control system could result in an oversizedvehicle driving through the tunnel due to a failure in the control system. Furthermore, a delayin the control system may result in the gate closing too late and letting the vehicle pass orhitting the vehicle as it passes through the gate. The new specification ensures that the gate isclosed until the monitoring system detects a vehicle smaller than the maximum size approachingthe tunnel. The gate is opened to let the vehicle pass, and then closed again. If the controlsystem fails to detect the vehicle the gate will not be opened. This leads to production delay,but ensures that the required safety level is maintained.

54

Page 69: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.3. PRELIMINARY HAZARD ANALYSIS (PHA)

9.3 Preliminary Hazard Analysis (PHA)

As illustrated in Figure 9.5, PHA is step 3 of the security-safety development process.(see Figure8.4). A PHA was performed in an early stage of the development life cycle. The results were usedas input to the safety requirements phase and to guide the design of the system architecture.

Implementation 6

Testing and Safety validation 7

Concept 1

Overall Scope Definition 2

Preliminary Hazard Analysis 3

Design 5

I t e r a

t e (

m o

r e i

n f o

r m a

t i o

n / d e

t a i l )

I t e r

a t e

Risk Management 4

Figure 9.5: Preliminary Hazard Analysis

The results of the PHA is documented in Table 9.1 and 9.2, and described briefly below.

The most serious hazard identified during the PHA was that the cutting robot is not stoppedwhen someone enters the safety zone. This may have several causes, such as hardware or softwarefailure in the LEGO system or in AIBO, natural disasters or sabotage making the PC or AIBOunavailable, or that the alert transmitted by AIBO is lost on its way to the LEGO system. Ina worst case scenario this hazard may result in the death of a person.

Table 9.1: Preliminary Hazard Analysis (PHA) ResultsID Hazard Consequences Causes Countermeasures1 Cutting robot does

not stop when per-son

Possible death or injury ofa person

AIBO fails to detect theperson

Code review to avoid log-ical SW errors

enters the safetyzone

The alert from AIBO doesnot reach the LEGO sys-tem

Control signals betweenAIBO and the PC con-troller, and

Natural disaster or sabo-tage make the PC and/orAIBO unavailable

between the PC controllerand LEGO system, Timestamps, Shielding of com-munication channels

Hardware failure in theLEGO system

Check battery status andactuator status

Software error in LEGOsystem

Code review

55

Page 70: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

Table 9.2: Preliminary Hazard Analysis (PHA) Results cont.ID Hazard Consequences Causes Countermeasures2 Cutting robot starts

working when a per-son is inside

Possible death or injury ofa person

A start is initiatedthrough the controlwindow

Prevent the cutting robotfrom being started fromthe control window

the safety zone Hardware failure in theLEGO system

Check battery status andactuator status

Logical SW error in thecontrol system

Code review

3 Cutting robot is notstopped when Offbutton is pressed

If the control system alsofails to stop the robotwhen someone enters thesafety zone:

Hardware failure in theLEGO system

Check battery status andactuator status

Possible death or injury ofperson

Software error in theLEGO system

Code review

4 Gate is not closedwhen intruder entersthe entrance area

Unauthorized person is al-lowed to enter the safetyzone and may get injuredif

Intruder is not detected Code review to avoid log-ical SW errors

he is not trained for op-erating in such environ-ments

LEGO system is not noti-fied about the intruder

Timestamps, Control sig-nals between AIBO andPC controller, and be-tween PC controller andLEGO system, Shieldingof communication chan-nels

Software error in theLEGO system

Code review

Hardware failure in theLEGO system

Check battery status andactuator status

5 A person gets in-jured by the gate

Injury The gate closes too lateand hits the person enter-ing the safety zone

Ensure that the gatecloses fast enough, in-clude sound signal

Exposed internal parts onthe gate

Avoid unnecessary expo-sure of internal parts inthe gate design

6 Person bumps intothe cutting robot

Injury Incautiousness of personworking in the safety zone

Always stop cutting robotwith the cutting arm in alowered positionRequire use of protectiveclothing, such as helmets

7 Cutting blade fallsoff the cutting arm

Person is hit by the blade.Possible death or injury

Defective blade or cut-ting arm and cutting armstopped in upright posi-tion

Always stop cutting robotwith the cutting arm in alowered position

Ensure good quality ofthe cutting arm designand the connections of theblade to the arm

Hazards caused by software errors in either the LEGO system, AIBO or the PC controller canbe reduced by performing code reviews in order to reveal logical errors in the software. Hazards

56

Page 71: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.3. PRELIMINARY HAZARD ANALYSIS (PHA)

caused by hardware failure in the LEGO system are difficult to avoid, but checks on batterystatus of the RCX and actuator status of the gate and cutting robot are possible hazard reducingactions.

To reduce the likelihood of messages being lost, the infrared communication channel can beshielded by enclosing the RCX and the IR tower in a separate room. The wireless LAN com-munication channel between the PC controller and the AIBO is more difficult to shield as theAIBO is located in the entrance area and must be able to move its head to get a total overviewof this area.

If messages still get lost it will be because of a broken communication link or unavailable assets.The likelihood of this hazard to occur can be reduced by introducing control signals and timestamps. Thus, if the LEGO system does not receive the control signals within a specified timelimit, it will time out and stop the cutting robot assuming that the PC controller is unavailable.Likewise, the PC controller will time out and send a stop signal to the LEGO system if thecontrol signal from AIBO is not received within the time limit.

To prevent the cutting robot from being started while someone is inside the safety zone, we canmake sure that it is impossible to start the robot from the control window. Since we assumethat only one person can be in the entrance area and safety zone at a time, it is not possiblethat the On button in the entrance area is pressed while someone is inside the safety zone.

There is a possibility that maintenance staff will get injured while performing maintenance onthe cutting robot, e.g. by accidentally bumping into the robot or if the cutting blade falls off thecutting arm. To reduce the likelihood of these hazards or the extent of the possible injuries, thecutting robot should always be stopped with the cutting arm in a lowered position, the designand construction of the cutting robot should ensure good quality, and the maintenance staffshould be required to wear protective clothing when entering the safety zone.

If the gate fails to close when an intruder enters the entrance area the intruder may enter thesafety zone. For people not trained and authorized to enter this zone, the likelihood of gettinginjured is high. The gate itself also constitutes a safety threat. If the gate closes too late ortoo slow an intruder trying to enter the safety zone may get hit by the gate. Further, exposedinternal parts of the gate may cause injury. To avoid these hazards we must make sure that thegate is closed fast enough and that the design and construction of the gate avoid unnecessaryexposure of internal parts.

57

Page 72: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

9.4 Requirement Specification

In step 4 of the development process we start the requirement and analysis activities as illus-trated in Figure 9.6. The functional and non-functional requirements of the system will bedescribed in this section. The functional requirements are listed in Chapter 9.4.1. Since thiswork concentrates on the relationship between safety and security, and not so much on the actualimplementation of the system, only the most relevant functional requirements are considered.Further, in a security-safety critical system one need to put particular emphasis on the safety andsecurity requirements. The safety and security requirements are considered as non-functionalrequirements and are described in Section 9.4.2.

Risk Management 4

Security requirements

4.2 Identify security threats

4.3

Evaluate Risk

4.5

Treat Risk

4.6

Safety requirements

4.1

Accept Risk

Analyse Risk 4.4

Identify safety

consequences 4.4.1

Identify likelihood

4.4.2

Estimate level of risk 4.4.3

No

Yes

Update system description and

requirements

4.7

Figure 9.6: Risk Management: Safety and security requirements

9.4.1 Functional Requirements

This section presents the most important functional requirements of the system. The require-ments presented are the list that were updated after the Security-HazOp in step 4.3 of thedevelopment process. However, requirements deleted after the analysis are indicated by using(a) Before Security-HazOp and (b) After Security-HazOp. The requirements are prefixed withthe letter F in order to indicate that the requirements are functional.

F 1 The LEGO cutting robot shall

F 1.1 stop operating if

i. the Off button in the entrance area is pressed.

ii. the “Stop cutting” button in the control window on the PC controller is pressed.

iii. the connection between the AIBO and the PC controller is lost.

iv. the connection between the PC controller and the LEGO system is lost.

(a) Before Security-HazOp:

v. someone enters the safety area.

(b) After Security-HazOp:

v. the gate is opened.

F 1.2 start operating if

i. the On button in the entrance area is pressed (by an authorized person after theSecurity-HazOP).

58

Page 73: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.4. REQUIREMENT SPECIFICATION

ii. the “Start cutting” button in the control window on the PC controller is pressed.

F 2 The RCX of the LEGO system shall

F 2.1 communicate with the PC controller through IR signals.

F 2.2 control

i. the lights

ii. the cutting robot

iii. the gate

iv. the gate lock

F 2.3 interpret data from

i. the On and Off buttons

ii. the sensors on the gate (touch sensors which are used to determine when the gateis opened or closed)

F 2.4 inform the PC controller about state changes of

i. the cutting robot (started/stopped)

ii. the gate (opened/closed)

F 3 The AIBO shall

F 3.1 communicate with the PC controller through wireless LAN

F 3.2 search for green man and pink ball.

F 3.3 notify the PC controller if

i. it detects an authorized person (green LEGO man) or an intruder (pink ball)entering the entrance area.

ii. it detects an authorized person or an intruder leaving the entrance area.

(a) Before Security-HazOp:

iii. it detects someone entering the safety zone.

F 4 The PC controller shall

F 4.1 communicate with the LEGO system through IR signals.

F 4.2 communicate with AIBO through wireless LAN.

F 4.3 send a start signal to the LEGO system when the start button in the control windowis pressed.

F 4.4 send a stop signal to the LEGO system when

i. the stop button in the control window is pressed.

ii. the connection to the AIBO is lost.

iii. the AIBO becomes unavailable.

(a) Before Security-HazOp:

iv. it receives an “entered safety zone” message from the AIBO.

F 4.5 send a “close gate” signal to the LEGO system when

i. the connection to the AIBO is lost.

(a) Before Security-Hazop:

ii. it receives an “intruder alert” from the AIBO.

59

Page 74: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

F 4.6 display status information when

i. communication to AIBO is lost.

ii. communication to LEGO system is lost.

iii. the cutting robot has started.

iv. the cutting robot has stopped.

v. intruder is detected in the entrance area.

vi. authorized person is detected in the entrance area.

vii. the cutting robot can not be started.

F 5 The gate shall

(a) Before Security-HazOp:

F 5.1 close if an intruder (pink ball) enters the entrance area.

F 5.2 open if the intruder leaves the entrance zone.

(b) After Security-HazOp:

F 5.1 unlock if an authorized person (green LEGO man) enters the entrance area.

F 5.2 open if the gate wheel in the entrance area is turned.

F 5.3 close if the authorized person leaves the entrance area without closing the gate.

F 5.4 lock if the authorized person leaves the entrance area.

F 5.5 close if it is open and the On button in the entrance area is pressed.

F 5.6 close and lock if the connection between the AIBO and the PC controller is lost.

F 5.7 close and lock if the connection between the PC controller and the LEGO system islost.

Extra features:

F 3.4 AIBO shall constantly sending view image of the entrance area to the PC controller

F 4.7 The PC controller shall display view from the camera in AIBO.

F 4.8 The PC controller shall display picture of the last detection of AIBO.

9.4.2 Non-Functional Requirements

This section presents the safety and security requirements being the non-functional requirementsof the system. Requirements for safety and security are the only non-functional requirementsassessed in this work. We only consider the security attributes confidentiality, integrity, avail-ability and authenticity because we want to address the relationship between security threatsand safety consequences in typical attack situations. Other attributes, such as reliability, arerelated to the actual system. The safety requirements shall ensure the safety of the system, andis elicited based on the safety critical system, as shown in Figure 9.7. This figure further showsthat the security requirements are elicited based on the security critical system, but they arealso affected by the identified safety requirements. The requirements are prefixed with the letterN in order to indicate that they are non-functional requirements.

60

Page 75: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.4. REQUIREMENT SPECIFICATION

Security critical system

Safety zone

Safety requirements

Security requirements

Figure 9.7: Elicitation of safety and security requirements

N 1 Safety requirements

N 1.1 The Cutting Robot shall not

i. be operating if a person is inside the safety zone.

ii. be operating if the control system is not activated and available.

iii. be operating if one or several of the assets of the control system stop workingproperly.

N 1.2 The Gate shall not

i. be open if the industry robot is operating.

ii. be unlocked when an intruder is in the entrance area.

iii. be unlocked when authorized staff is not in the entrance area or inside the safetyzone.

N 1.3 The Control System shall not

i. be initiated when people are inside the safety zone (if so, the system will notknow that the zone is not empty, and the industry robot may be started).

N 2 Security requirements

N 2.1 Confidentiality

i. Only authorized personel shall have access to the control window on the PCcontroller, and only administrators should have administrative access to the PCcontroller. Administrative access includes access to the source code and to thecontrol parameters of the system.

N 2.2 Integrity

i. The data exchange between the AIBO and the PC controller shall not be cor-rupted or altered.

ii. The data exchange between the PC controller and the LEGO system shall notbe corrupted or altered.

iii. The AIBO shall not be corrupted or altered.

iv. The LEGO system shall not be corrupted or altered.

v. The PC controller shall not be corrupted or altered.

N 2.3 Availability

i. The control system shall be available 100% of the time the system is in runningmode. However, we allow maintenance as long as the cutting robot is stoppedwhile the control system is unavailable.

61

Page 76: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

ii. Data exchanged between AIBO and PC controller shall not be lost.

iii. Data exchanged between PC controller and LEGO system shall not be lost.

N 2.4 Authenticity

i. Authorized users must log on to the system using user name and password (weakauthentication).

9.4.3 Use Cases

The functional requirements are illustrated with the use of UML use cases [10]. The main usecases are shortly described in Table 9.3, and the actors involved are described in Table 9.4.

Table 9.3: Main use casesUse case Short descriptionStop cutting robot The LEGO cutting robot shall stop operating if:

- the Off button in the entrance area is pressed.

- the “Stop cutting” button in the control window on the PC controlleris pressed.- the connection between AIBO and the PC controller is lost.

- the connection betweeen the PC controller and the LEGO system islost.

- the gate is openedStart cutting robot The LEGO cutting robot shall start operating if:

- the On button in the entrance area is pressed.

- the “Start cutting” button in the control window on the PC controlleris pressed.

Open gate The gate shall open if the gate wheel in the entrance area is turned.Close gate The gate shall close if:

- the authorized person leaves the entrance area without closing the gate.

- it is open and the On button in the entrance area is pressed.

- the connection between the AIBO and the PC controller is lost.

- the connection between the PC controller and the LEGO system islost.

Unlock gate The gate shall unlock if an authorized person enters the entrance area.Lock gate The gate shall lock if:

- the authorized person leaves the entrance area.

- the connection between the AIBO and the PC controller is lost.

- the connection between the PC controller and the LEGO system islost.

Notify PC con-troller

The AIBO shall notify the PC controller if:

- it detects an authorized person or an intruder entering the entrancearea.

- it detects an authorized person or an intruder leaving the entrancearea.

The use case diagram in Figure 9.8 depicts the overall functionality of the system and the actorsinvolved. Each use case is described in appurtenant use case specifications in Tables 9.5 to 9.15.

62

Page 77: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.4. REQUIREMENT SPECIFICATION

Table 9.4: Actors involved in the use casesActor DescriptionIntruder An unauthorized person. The intruder is not allowed to enter the safety

zone, and should not dwell in the entrance area.Authorized staff An authorized person, which is allowed to enter the safety zone for main-

tenance.Cutting robot actu-ator

The motor of the cutting robot.

Gate actuator The motor of the gate.Gate lock actuator The motor of the locking mechanism on the gate.AIBO The monitoring robot.

AIBO

Authorized staff

Intruder

Gate actuator

Unlock gate

Open gate

Start cutting robot

Stop cutting robot

Lock gate

Close gate

Cutting robot actuator

Gate lock actuator

«uses»

Notify PC controller

Figure 9.8: Use case diagram: Overall system functionality

Table 9.5: Use case: Open gateActor Authorized staff, gate actuatorShort descrip-tion

Authorized staff is allowed to open the gate into the safety zoneby turning the gate wheel in the entrance area. When he opensthe gate the cutting robot stops working.

Pre-conditions AIBO has detected staff in the factory and the gate has beenunlocked.

Post-conditions The gate is open and the cutting robot has stopped working.Basic flow 1. The authorized staff turn the wheel for opening the gate.

2. The cutting robot stops working.

3. The gate opens.Alternative flow 1. Unauthorized staff tries to turn the wheel for opening the gate.

2. The gate is locked, thus the gate will not open.

63

Page 78: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

Table 9.6: Use case: Close gateActor Authorized staff, gate actuatorShort descrip-tion

When the authorized staff has finished the maintenance inside thesafety zone, he can close the gate by pressing the On button inthe entrance area. If he leaves the entrance area without closingthe gate, the gate will close automatically because AIBO sendsa message to the PC controller that he left. (A personal codeshould be entered when attempting to open and close the gate,and only the person opening should be allowed to close.)

Pre-conditions The gate is open.Post-conditions The gate is closed.Basic flow 1. The authorized staff press the button for closing the gate.

2. The gate closes.Alternative flow 1. The authorized staff leaves the entrance area leaving the gate

open.

2. The AIBO alerts the PC controller.3. The gate closes and locks.

Table 9.7: Use case: Lock gateActor Authorized staff, gate lock actuator.Short descrip-tion

When the authorized staff leaves the entrance area, the gate shalllock so that nobody can enter the safety zone.

Pre-conditions AIBO is connected, authorized staff is in the entrance area andgate is unlocked.

Post-conditions Gate is locked.Basic flow 1. AIBO detects that the authorized staff leaves the entrance

area.

2. AIBO sends a message to the PC controller that the authorizedstaff has left the entrance area.

3. The PC controller sends a signal to the RCX of the LEGOsystem that the gate shall be locked.4. The RCX sends a lock signal to the gate lock actuator.

5. The gate is locked.Alternative flow 4.1 If the gate is opened, the RCX sends a close signal to the gate

actuator.

4.2 The RCX sends a lock signal to the gate lock actuator.

Table 9.8: Use case: Unlock gateActor Authorized staff, Gate lock actuator.Short descrip-tion

When authorized staff enters the entrance area, the gate shallunlock so that they can enter the safety zone for maintenance.

Pre-conditions AIBO is connected and gate is locked.Post-conditions The gate is unlocked.Basic flow 1. AIBO detects that the authorized staff enters the entrance

area.

2. AIBO sends a message to the PC controller that authorizedstaff has entered the entrance area.3. The PC controller sends a signal to the RCX of the LEGOsystem that the gate shall be unlocked.

4. The RCX sends an unlock signal to the gate lock actuator.

5. The gate is unlocked.Alternative flow

64

Page 79: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.4. REQUIREMENT SPECIFICATION

Table 9.9: Use case: Notify PC controllerActor AIBOShort descrip-tion

The AIBO shall notify the PC controller if it detects an intruderor an authorized person in the entrance area.

Pre-conditions AIBO is connected.Post-conditions The PC controller has received a message about intruder or au-

thorized person in the entrance area.Basic flow 1. AIBO detects an intruder or an authorized person.

2. AIBO sends a message about the detection to the PC con-troller.

Alternative flow

As depicted in Figure 9.9, the use case “Stop cutting robot” is decomposed into sub use cases.Each of the sub use cases are described in the following use case specifications.

Authorized staff

Intruder

Stop initiated by stop button in control

window

Stop initiated by OFF button in entrance area

Cutting robot actuator

Stop if connection between AIBO and PC lost

Stop if connection between PC and LEGO system

lost

Figure 9.9: Decomposed use case diagram: Stop cutting robot

Table 9.10: Use case: Stop initiated by Off button in entrance areaActor Authorized staff, Intruder, Cutting robot actuator.Short descrip-tion

The cutting robot can be stopped by pressing the Off button inthe entrance area.

Pre-conditions The cutting robot is operating.Post-conditions The cutting robot is not operating.Basic flow 1. The Off button in the entrance area is pressed.

2. The RCX receives a stop signal from the Off button.3. The cutting robot stops cutting.

Alternative flow

65

Page 80: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

Table 9.11: Use case: Stop initiated by stop button in control windowActor Authorized staff, Cutting robot actuator.Short descrip-tion

The cutting robot can be stopped by pressing the “Stop cutting”button in the control window on the PC controller.

Pre-conditions The cutting robot is operating, and the communication betweenthe PC controller and the LEGO system is working properly.

Post-conditions The cutting robot is not operating.Basic flow 1. The “Stop cutting” button in the control window is pressed.

2. The PC controller sends a signal to the RCX of the LEGOsystem that the cutting robot shall stop cutting.

3. The RCX sends a stop signal to the cutting robot actuator.

4. The cutting robot stops cutting.Alternative flow

Table 9.12: Use case: Stop if connection between AIBO and PC lostActor Cutting robot actuator, Gate actuator, Gate lock actuator.Short descrip-tion

If the connection between AIBO and the PC controller is lost, thecutting robot shall stop operating, and the gate shall be closedand locked.

Pre-conditionsPost-conditions The cutting robot is not operating and the gate is closed and

locked.Basic flow 1. The PC controller detects that the connection to AIBO is lost.

2. The PC controller sends a signal to the RCX of the LEGOsystem that a fatal situation has occured.

3. The RCX sends a stop signal to the cutting robot actuator.

4. The cutting robot stops cutting.Alternative flow 5. If the gate is open, the RCX sends a close signal to the gate

actuator.

6. The gate is closed.

7. If the gate is unlocked, the RCX sends a lock signal to the gatelock actuator.

8. The gate is locked.

Table 9.13: Use case: Stop if connection between PC and LEGO system lostActor Cutting robot actuator (, gate actuator, gate lock actuator?).Short descrip-tion

If the communication between the PC controller and the LEGOsystem is not working properly, the cutting robot shall stop work-ing (and the gate shall be closed and locked).

Pre-conditionsPost-conditions The cutting robot is not working and the gate is closed and locked.Basic flow 1. The RCX times out when waiting for signals from the PC

controller.

2. The RCX sends a stop signal to the cutting robot actuator.

3. The cutting robot stops cutting.Alternative flow 4. If the gate is open, the RCX sends a close signal to the gate

actuator.

5. If the gate is unlocked, the RCX sends a lock signal to the gatelock actuator.

66

Page 81: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.4. REQUIREMENT SPECIFICATION

The use case “Start cutting robot” is further decomposed into sub use cases, as depicted inFigure 9.10. The sub use cases are described in the use case specifications below.

Authorized staff

Start initiated by start button in control

window

Start initiated by ON button in entrance area

Cutting robot actuator

Figure 9.10: Decomposed use case diagram: Start cutting robot

Table 9.14: Use case: Start initiated by On button in entrance areaActor Authorized staff, Cutting robot actuator.Short descrip-tion

The cutting robot can be started by authorized staff pressing theOn button in the entrance area. (The On button is enabled whenAIBO detects authorized staff entering the factory, and disabledwhen they leave.)

Pre-conditions AIBO is connected, the RCX is booted, the communication be-tween the PC controller and the LEGO system is working prop-erly, AIBO has detected the authorized staff entering the entrancearea, and the gate is closed.

Post-conditions The cutting robot is operating.Basic flow 1. The On button in the entrance area is pressed.

2. The RCX receives a start signal from the On button.

3. The cutting robot starts operating.Alternative flow

Table 9.15: Use case: Start initiated by start button in control windowActor Authorized staff, Cutting robot actuator.Short descrip-tion

The cutting robot can be started by pressing the “Start cutting”button in the control window on the PC controller.

Pre-conditions The communication between the PC Controller and the LEGOsystem is working properly, AIBO is connected, and the gate isclosed.

Post-conditions The cutting robot is operating.Basic flow 1. The “Start cutting” button in the control window is pressed.

2. The PC controller sends a signal to the RCX of the LEGOsystem that the cutting robot shall start cutting.

3. The RCX sends a start signal to the cutting robot actuator.

4. The cutting robot starts cutting.Alternative flow

67

Page 82: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

9.5 Identify Security Threats

To identify security threats, which is step 4.3 in the development process (see Figure 9.11), a“Security-HazOP” is used. “Security-HazOp” is based on traditional use of HazOP within thesafety domain adapted for use in the security domain. The modified HazOp method is describedin the following section.

Risk Management 4

Security requirements

4.2 Identify security threats

4.3

Evaluate Risk

4.5

Treat Risk

4.6

Safety requirements

4.1

Accept Risk

Analyse Risk 4.4

Identify safety

consequences 4.4.1

Identify likelihood

4.4.2

Estimate level of risk 4.4.3

No

Yes

Update system description and

requirements

4.7

Figure 9.11: Identify security threats

9.5.1 Security-HAZOP

Security-HazOp is published by the IST-project CORAS, and is a version of HazOp adapted tothe security domain. The adaption focuses in particular on supporting identification of securitythreats when security is regarded as a safety issue in a safety context [67]. The reason fordeveloping this method was the increased use of Information and Communication Technology(ICT)-systems and the Internet as a forum to communicate and do business. This combinationintroduces serious concerns regarding security as a possible cause of safety problems. As part ofthe development of the security-HazOp, several methods were evaluated for use in the securitydomain. The evaluation showed that the HazOp principles seemed well suited for the purpose,assuming that adequate guidewords could be established [67].

The aim of Security-HazOp is to identify critical security-related deviations from intended be-haviour, with focus on the confidentiality, integrity and availability (the CIA attributes). As intraditional HazOp, the analysis is performed in a brainstorm setting using a set of guidewordsand attributes. The attributes used in this context are the negation of the CIA attributes;disclosure, manipulation and denial. The guidewords used are divided into two groups, pre-guidewords and post-guidewords, to be able to combine more than one guideword with eachattribute. Hence, the structure of the security-HazOp expressions becomes

“Pre-Guideword Attribute of Component due to Post-Guideword”.

Table 9.16 provides some example combinations of guidewords and attributes that [67] suggestsas a starting point when using the Security-HazOp.

The components to be included in the security-HazOp must constitute entities for which theattributes confidentiality, integrity and availability are meaningful. [67] suggests that the varioustypes of information in a system and the functions the system perform should be included. In

68

Page 83: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.5. IDENTIFY SECURITY THREATS

addition, physical entities may also be meaningful in some cases. For more detailed informationon the Security-HazOp, the reader is referred to [67].

Table 9.16: Basic guidewords and attributes in security-HazOp [67].Pre-Guideword Attribute Post-Guideword

Deliberate Disclosure Insider

Unintentional Manipulation of COMPONENT Outsider

Denial due to Technical failure

9.5.2 Execution of the Security-HazOp

Before conducting the analysis guidewords, attributes and components were selected. The finalselection is listed in Table 9.17. The components chosen were identified as being the mostimportant and most critical parts of the system; the AIBO, the PC controller, the RCX andthe communication links (WLAN and IR). The guidewords were chosen such that they wouldmake possible the representation of both the various sources of threat (the threat agents) andto specify whether the threat is deliberate or unintentional. The negations of the non-functionalsecurity requirements were used as attributes:

Confidentiality ⇒ Disclosure

Integrity ⇒ Manipulation

Availability ⇒ Denial,Delay

Authenticity ⇒ Fabrication,Masquerade

Table 9.17: Guidewords, components and attributes used in the security-HazOp.Pre-Guideword Attribute Components Post-Guideword

Deliberate Disclosure AIBO Insider

Unintentional Manipulation PC controller Outsider

Denial Communication links (WLAN and IR) Technical failure

Fabrication LEGO system Virus

Delay Physical blocking

9.5.3 Results of the Security-HazOp

The results from the Security-HazOp were documented in forms as illustrated in Table 9.18. Itproved not to be necessary to use the post-guidewords in order to identify all possible causes. Wehave therefore not included threat agent as a separate column. In the reminder of this sectionthe most important results of the Security-HazOp are discussed. For the complete version ofthe results the reader is referred to Appendix C. For clarity, the results are presented sepa-rately according to each of the possible security breaches; breaches of confidentiality, integrity,availability and authenticity.

69

Page 84: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

Table 9.18: Documentation form for the Security-HazOpBreaches of <attribute>

Expression Security threat Consequences Causes Countermeasures

Deliberatefabrica-tion/masqueradeof AIBO

Unauthorizeduser/componentacts as AIBOand fabricatesmessages

Masquerade AIBO sends messagethat staff or intruder is not inentrance area or safety zone anylonger when they still are present,which can lead to possible death orinjury

Masquerade AIBO(false AIBO hastaken over the roleof the real AIBO

Implement au-thenticationmechanism be-tween AIBO andPC controller

Breaches of confidencialityThe security threats related to breaches of confidentiality include that unauthorized persons getaccess to messages transmitted in the communication channels as well as the data and settings inthe AIBO, LEGO system and PC controller. The identified security threats related to breachesof confidentiality can be found in Table C.1.

Breaches of integrityBreaches of integrity include modification of messages transmitted in the communication chan-nels and manipulation of AIBO, LEGO system and the PC controller to ignore received messagesand to not send important commands. The identified security threats related to breaches of in-tegrity can be found in Table C.3.

Breaches of availabilityThe availability is threatened if messages in the communication channels are lost or delayed.Furthermore, if the AIBO, LEGO system or PC controller are prevented from performing theirnormal operation it is a breach of availability. The identified security threats related to breachesof availability can be found in Table C.4.

Breaches of authenticityThreats to authenticity that were identified was the injection of false messages into the commu-nication channels, as well as masquerading of AIBO or PC controller. The identified securitythreats related to breaches of authenticity can be found in Table C.6.

9.6 Analyse Risk

Analyse risk corresponds to step 4.4 of the development process , as illustrated in Figure 9.12.Analyse risk includes identification of safety consequences (step 4.4.1), their likelihood (stage4.4.2) and the estimation of the level of risk (stage 4.4.3).

70

Page 85: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.6. ANALYSE RISK

Risk Management 4

Security requirements

4.2 Identify security threats

4.3

Evaluate Risk

4.5

Treat Risk

4.6

Safety requirements

4.1

Accept Risk

Analyse Risk 4.4

Identify safety

consequences 4.4.1

Identify likelihood

4.4.2

Estimate level of risk 4.4.3

No

Yes

Update system description and

requirements

4.7

Figure 9.12: Analyse risk

In Appendix D, safety consequences and their consequence values, likelihood values and riskclassification are listed for each of the identified security threats. For the identification activities,value tables adopted from the UK MoD standard 00-56 [51] were used. To estimate the level ofrisk we used classification defined in IEC 61508 [34].

9.6.1 Identify Safety Consequences

The identification of safety consequences corresponds to step 4.4.1 in the development process(see Figure 9.13). Safety consequences are identified for each of the security threats identifiedduring the security-HazOp.

Analyse Risk 4.4

Identify safety

consequences 4.4.1 Identify

likelihood 4.4.2

Estimate level of risk 4.4.3

Figure 9.13: Identify safety consequences

For classifying the threats in terms of severity, the classification table in Figure 4.2, adaptedfrom the UK Ministry of Defence for military computer-based systems [51], were used. Even ifthe LEGO prototype are no real system, consequences as death and injury are used. Withoutthis relationship to the simulated real world system, an analysis of safety aspects would bemeaningless as it would be impossible to classify the severity of the identified threats. Theoriginal table from [51] was adjusted to not include multiple deaths and injuries. This was doneto reflect the fact that a threat in the system at most may result in the death or injury of oneindividual, as it is assumed that only one person can be in the entrance area and safety zone ata time.

The identified safety consequences are fully documented in Appendix D, but we discuss the mostimportant results below.

Confidentiality is not the most important security attribute in this study as the data in thesecurity-safety critical system is not sensitive. If an unauthorized party gains access to informa-

71

Page 86: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

tion and assets of the system, but is not able to modify them, there will be no consequences forthe safety of the system. Hence, breaches of confidentiality do not directly affect the safety ofthe system. However, breaches to confidentiality open up for breaches to integrity, availabilityand authenticity, and have thereby indirect consequences for safety.

If the AIBO is manipulated to ignore intruders, the gate fails to close and the intruder may walkinside the safety zone and is hence subject to injury. If the AIBO is manipulated to ignore peopleentering the safety zone, the cutting robot fails to stop, which may lead to the death of thisperson. The same also applies for the case where the PC controller is manipulated. If it ignoresthe alerts from AIBO, the LEGO system is not notified and thus the gate is not closed andthe cutting robot is not stopped. The messages transmitted over the communication channelscan also be manipulated. This may in worst case result in the LEGO system not stopping thecutting robot when someone enters the safety zone due to alteration of a stop signal.

If the AIBO, which represents the monitoring system of the security-safety critical system,becomes unavailable an intruder entering the entrance area or a person entering the safety zonewill not be detected. Hence the gate will not close and the cutting robot will not stop operating.In a worst case scenario, the consequence of this security breach may be the death of a person.The same also applies if the PC controller becomes unavailable since this is the link between theAIBO and the LEGO system. In the case of the wireless LAN, interference of the radio signals byother senders may cause messages from AIBO to the PC to be lost. The IR communication linkbetween the PC controller and the LEGO system can also experience interference. If one of thecommunication channels becomes unavailable or messages transmitted over the communicationchannels are lost or delayed, the consequence may be that the gate fails to close or closes toolate or that the cutting robot fails to stop or stops too late. This may result in death or injuryof a person.

Except for false start messages and disconnect signals to AIBO, false messages inserted intothe communication channels does not affect the safety of the system. In the case of a falsestart message the cutting robot may start while someone is inside the safety zone. A falsedisconnect signal to AIBO makes AIBO unavailable. Other messages, which can be “intruderalerts”, “entered safety zone” messages, stop messages or “close gate” messages, will only resultin the gate closing or the cutting robot stopping needlessly.

9.6.2 Identify Likelihood

For each safety consequence identified in the previous step, a likelihood value is estimated. Thelikelihood value represents the likelihood of occurence of the security threat leading to the safetyconsequence. As illustrated in Figure 9.14, this is step 4.4.2 in the development lifecycle.

Analyse Risk 4.4

Identify safety

consequences 4.4.1 Identify

likelihood 4.4.2

Estimate level of risk 4.4.3

Figure 9.14: Identify likelihood

72

Page 87: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.6. ANALYSE RISK

The likelihood ranges used when categorizing hazards according to their likelihood to occur isshown in Table 4.3. The likelihood of the security threats are documented in Appendix D. Themost important results are presented below.

The probability that an unauthorized person gains access to the programs and network settingsof the AIBO is very low as it is retained on a memory stick inside the AIBO. In order to ac-cess and modify the application code , the memory stick must be removed from the AIBO andinserted into a PC by using a memory stick adapter. The probability of unauthorized accesson the PC controller on the other hand is higher, especially if there is no access control mech-anism. Furthermore, the communication channels are highly exposed because of the feasabilityof eavesdropping.

Breaches of integrity of the wireless LAN are more complicated to carry out, as it concernsradio signals sent through the atmosphere. To modify a transmitted message before it reaches itsintended receiver, the receiver must be blocked or in some other way be prevented from receivingmessages from the transmitter. Another receiver placed within reach of the transmitter can thenreceive the message and modify it before forwarding it. If the original receiver is then unblockedagain before the message is forwarded, it will receive the modified message. The probability ofthis happening between the AIBO and PC is considered to be very low.

The probability of breaches of integrity of the infrared communication channel between the PCcontroller and the LEGO system is not very high. However, IR signals are easier to block thanradio signals. By placing another receiver between the IR tower and the RCX, the transmit-ted messages may be received, altered and forwarded by the intermediate receiver/transmitter.Furthermore, to be able to modify the transmitted messages in order to do harm, the attackermust know how the system works and what kind of messages are used, for instance that theletter “S” means start.

The probability of the AIBO or PC controller becoming unavailable is fairly high as this can becaused by several incidents, e.g. sabotage, natural disaster, technical failure, denial of service(DoS) attack, theft, and shut down of AIBO/PC. If something is blocking or interfering withthe signals in the communication channels the probability is high that the messages is lost.Further, it is easy to insert spurious messages into the communication channels. However, toinsert messages with sensible meaning in order to do harm, the attacker must know the systemand what kind of messages are used.

73

Page 88: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

9.6.3 Estimate Level of Risk

Based on the consequence and likelihood values from the two previous steps, the security threatsand their safety consequences are assigned to a risk class. This represents step 4.4.3 of thesecurity-safety development process (see Figure9.15).

Analyse Risk 4.4

Identify safety

consequences 4.4.1 Identify

likelihood 4.4.2

Estimate level of risk 4.4.3

Figure 9.15: Estimate level of risk

IEC 61508 [34] Part 5 defines four risk classes (see Table 4.4) and suggests relationships betweenthe risk classes and the severity and frequency of the hazards (see Table 4.5). The result of therisk estimation can be found in Appendix D.

9.7 Evaluate Risk

After assigning the security threats and their safety consequences to risk classes, a risk evaluationis performed to decide which are acceptable and which are not. Each risk is evaluated againstthe acceptance criteria identified. This constitutes step 4.5 of the development lifecycle (seeFigure 9.16).

Risk Management 4

Security requirements

4.2 Identify security threats

4.3

Evaluate Risk

4.5

Treat Risk

4.6

Safety requirements

4.1

Accept Risk

Analyse Risk 4.4

Identify safety

consequences 4.4.1

Identify likelihood

4.4.2

Estimate level of risk 4.4.3

No

Yes

Update system description and

requirements

4.7

Figure 9.16: Evaluate risk

Risk in risk class I, II and III were considered not acceptable and had to be treated. Riskassigned to class IV were considered acceptable, and did not need any treatment.

74

Page 89: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.8. TREAT RISK

9.8 Treat Risk

The risks considered not acceptable in the previous stage need to be treated. Risk treatment isperformed in step 4.6 of the risk management stage, as illustrated in Figure 9.17.

Risk Management 4

Security requirements

4.2 Identify security threats

4.3

Evaluate Risk

4.5

Treat Risk

4.6

Safety requirements

4.1

Accept Risk

Analyse Risk 4.4

Identify safety

consequences 4.4.1

Identify likelihood

4.4.2

Estimate level of risk 4.4.3

No

Yes

Update system description and

requirements

4.7

Figure 9.17: Treat risk

The principles for treating risk are described in chapter 4.6.

The listing below shows the safeguards that were considered necessary to introduce in order toensure an acceptable level of safety of the system according to the results from evaluation of risk.

RedesignWhile in normal operational mode the cutting robot is operating with the gate open. This wasidentified as a hazardous state. Due to the severe consequences and high likelihood of failureto stop the cutting robot when someone enters the safety zone, a redesign is recommended. Tomove the system to a safer state the gate should always be closed while the cutting robot isoperating. To still allow for maintenance, the gate can be opened and the cutting robot stoppedwhen AIBO detects an authorized person in the entrance area, and close the gate again whenthe authorized person leaves the area. However, as people may enter the entrance area for otherreasons than entering the safety zone this would have a negative effect on the productivity ofthe factory. Hence, a lock could be applied to the gate. In normal operational mode the gate isclosed and locked. When an authorized person enters the entrance area the gate is unlocked andit can be opened manually by the person if necessary. Opening the gate will stop the cuttingrobot. When the authorized person has finished the maintenance work and left the safety zonehe can close the gate manually. The cutting robot can then be restarted. When the authorizedperson leaves the entrance area the gate is locked. If he leaves without closing the gate manually,the gate will close automatically.

Prevent start when gate is openBefore the redesign, it was suggested to prohibit the cutting robot from being started fromthe control window because this could lead to someone starting it while a person was insidethe safety zone. However, after redesigning the system such that the cutting robot is stoppedautomatically when the gate is opened, this is no longer necessary. The system should insteadprohibit the cutting robot from being started when the gate is opened. Due to the fact thatthe gate can not be closed from the control window and it is assumed that only one person

75

Page 90: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

can be in the entrance area and safety zone at a time, no one except the person opening thegate is allowed to close it again. When this person leaves the area, the gate will close and lockautomatically.

Access controlAn access control mechanism should be implemented in the PC controller to protect the integrityof the PC controller and ensure that only legitimate parties have access to the control windowand the source code. The users of the system could be divided into three user groups, each withdifferent access privileges:unauthorized - not allowed to log inauthorized - allowed to log in and control factory through control window (GUI)super user - allowed to log in and control factory as well as editing the source code of the ap-plicationIn the prototype the windows login is considered to be sufficiently access control.

Encryption and timestampsThe messages transmitted over the wireless LAN should be encrypted and have a time stampattached. This will not eliminate or reduce the threat of integrity breaches, but since the receiverthen can tell if a received message has been altered, it will control it to reduce the likelihoodof the threat leading to an accident. This safeguard is omitted in our prototype due to timelimitation, but is strongly recommended for prospective further work with implementation ofthis system in a security-safety context.

Stop when asset is unavailable or the connection lostThe PC controller should be able to detect if the AIBO becomes unavailable or if the connectionbetween them is lost. If so, the PC controller should send a message to the LEGO systemand order it to shut down. Furthermore, the LEGO system should be able to detect if the PCcontroller becomes unavailable or the connection is lost, and in that case stop the cutting robotand close and lock the gate.

Secure storage of memory stickTo protect the memory stick from being tampered with, it should be stored in a secure placewhen not in use. Furthermore, the part of the AIBO were the memorystick is inserted shouldbe shielded as much as practically feasible without preventing the AIBO in its monitoring task.

Shielding of IR communication linkThe IR communication link between the PC controller and the LEGO system can be shieldedby placing the IR tower of the PC and the RCX of the LEGO system close together and shieldthem from the surroundings by enclosing walls. This safeguard was identified already during thePHA. By shielding the communication link the probability of messages getting lost is reduced,but not eliminated.

Prohibit other electrical equipmentIt is impossible to completely eliminate the threat of messages being lost, but to reduce thefrequency of lost messages other electrical equipment with radio senders/transmitters shouldnot be allowed within a certain distance of the system.

76

Page 91: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.8. TREAT RISK

9.8.1 Update system description and requirements

After the introduction of new safeguards the system description and the functional requirementsmust be updated, and the risk management phase repeated. Updating is step 4.7 in the devel-opment process, as illustrated in Figure 9.18. The updates are documented in Sections 9.2.2and 9.4.1, respectively.

Risk Management 4

Security requirements

4.2 Identify security threats

4.3

Evaluate Risk

4.5

Treat Risk

4.6

Safety requirements

4.1

Accept Risk

Analyse Risk 4.4

Identify safety

consequences 4.4.1

Identify likelihood

4.4.2

Estimate level of risk 4.4.3

No

Yes

Update system description and

requirements

4.7

Figure 9.18: Update system description and requirements

77

Page 92: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

9.9 System Design

This section describes the design of the prototype developed in this thesis. Illustrations andUML diagrams [10] are used to ease the comprehensiblity. This is step 5 in the developmentprocess (see Figure 9.19). After designing the prototype, the risk management step shouldbe repeated in order to avoid costly changes later in the developement process. Due to timelimitation this is not carried out in this thesis, rather the design was continuously updated asobstacles and conspicuous faults were unveiled during implementation.

Implementation 6

Testing and Safety validation 7

Concept 1

Overall Scope Definition 2

Preliminary Hazard Analysis 3

Design 5

I t e r

a t e

( m

o r e

i n

f o r m

a t i o

n / d

e t a

i l )

I t e r

a t e

Risk Management 4

Figure 9.19: Design

9.9.1 Overall Architecture

The prototype of the security-safety critical system consists of three computing units: a LEGORCX running on Hitachi H8300 CPU, an AIBO with a MIPS 64-bit RISC processor, and astandard PC controller. There are two communication interfaces: between the LEGO RCXand PC, based on infrared (IR) serial communication, and between the PC and AIBO, basedon wireless LAN. The PC communicates over the IR channel through an IR tower attached tothe serial port of the PC. Figure 9.20 depicts the architecture of the software and hardwarecomponents of the implemented system. In the bottom row of the figure, which represents thedata link and physical layers of the OSI Model (see Chapter 5.1), the hardware componentsof the system and the wireless ethernet are contained. The operating systems running on theRCX, PC and AIBO are contained in the layer composed of the network and transport layersalong with the TCP/IP protocol and the LNP protocol included in the legOS kernel. Thetop row represents the session, presentation and application layers, and contains the softwareapplications residing in the RCX, PC and AIBO, as well as the telnet protocol. To be able touse the LNP protocol on the PC side an external utility (IR tool), which must include the LNPpackage, is implemented. The IR, and hence the LNP protocol, is contained in the applicationlayer of the PC, while in the RCX the LNP protocol is contained in the network layer.

The software deployed on these assets are depicted in the deployment diagram in Figure 9.21.The factory application on the LEGO RCX, which is further described in Section 9.9.3, isresponsible for controlling the LEGO system. The ballTrackingHead application in AIBO is

78

Page 93: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.9. SYSTEM DESIGN

LegOS

Factory

IR tower

IR port RCX

LNP

IR Ball Telnet client

Serial port PC

LNP

Wireless ethernet

Sony AIBO

BallTrackingHead Telnet server

TCP/IP OPEN-R Windows TCP/IP

Wireless ethernet

PoP PoP

Session, presentation and application layer

Data link and physical layer

Network and transport layer

Figure 9.20: Overall architecture of the system

responsible for monitoring the entrance area and alerting the PC controller when it detects anintruder or an authorized person. The modules of this application are described in Section 9.9.2,along with the different states of the AIBO. The PC controller represents the link between theAIBO and the LEGO RCX. The Ball3 application on the PC controller starts on demand thetelnet and ir tools for communicating with AIBO and LEGO RCX. When AIBO sends an alertabout a detected intruder or authorized person, this application is responsible for passing it onto the LEGO system. The design of the application and the possible states of the PC controllerare described in Section 9.9.4. The cutting robot and the gate are actuators controlled by theRCX. They are not computing units, and hence do not contain any software.

79

Page 94: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

IR tower {Role = device}

Wireless LAN {Role = Communication link}

Cutting robot {Role = device}

Gate {Role = device}

IR {Role = Communication link}

RCX {Role = processor}

factory

PC {Role = processor}

ball3.exe

telnet.exe

ir.exe

AIBO {Role = processor}

BallTrackingHead

PowerMonitor

OVirtualRobot

MovingLegs2

MovingHead2

LostFoundSound

Figure 9.21: Deployment of the components in the system (UML deployment diagram)

9.9.2 AIBO

Figure 9.22 depicts the different states of AIBO. Initially, AIBO is in the state “Off” and assumedequipped with a fully charged battery pack, a wireless LAN card and a memory stick containingthe proper software. When the pause button on AIBO’s chest is pushed it moves to state “On”,which makes it possible to connect to it through the wireless LAN. When the PC controllerinitiates a telnet connection to AIBO, the state entered is called “Connected, looking for staffor intruder”. In this state, the surveillance program of AIBO is available for the PC controller.If AIBO detects an intruder or an authorized person (staff), it keeps following him by movingits head such that he remains in the center of the camera focus. When AIBO lose track of theintruder/staff, it returns to the state looking for staff or intruder. The AIBO can be shut downfrom any state by pushing the pause button.

80

Page 95: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.9. SYSTEM DESIGN

Off On, not connected

Following intruder

Connected, looking for staff or intruder

Following staff

Pause button

Staff lost

Staff detected

Intruder lost

Intruder detected

Pause button

Connection initiated

Connection lost

Pause button

Pause button

Figure 9.22: State diagram: AIBO

The BallTrackingHead application, illustrated in Figure 9.23, initializes AIBO after boot, andcontrols its actuators and sensors in order to permanently monitor the entrance area.

MovingLegs2

LostFoundSound

OVirtualRobot (OPEN-R)

MovingHead2

PowerMonitor

BallTrackingHead

MovingHead

MovingLegs

LostFoundSound

Move

Play

Joint

FbkImageSensor

Sensor

Telnet Console (OPEN-R)

Move

Wireless TCP/IP connection

PC

Figure 9.23: Component diagram: BallTrackingHead

81

Page 96: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

It consists of multiple objects, each of which is implemented by a separate class. The objectshave the following functionality:

PowerMonitor Monitors the battery power level, the Pause button, and related events,reports the status to the console, and shuts down AIBO when appropri-ate.

MovingHead2 Moves the head of the survelliance robot that contains the camera inorder to monitor the whole entrance area permanently.

MovingLegs2 Initializes AIBO into a standard monitoring pose by stretching all andits rear legs after the startup.

LostFoundSound Notifies the user by playing an alert sound each time the authorizedstaff or intruder is detected in the visible frame.

BallTrackingHead The main client object that gives commands to the server objects namedabove and permanently processes the vision image from AIBO’s camera.Whenever the amount of the specified color (either green - for the staff,or pink for the intruder) in the camera view exceeds the threshold, anevent is printed on the telnet console and thus becomes available for PCcontroller. In addition, the robot moves its head so that the detectedarea remains in the center of the cameras focus.

OVirtualRobot Is not part of the BallTrackingHead application, but serves as an inter-face between the application and the OPEN-R.

Objects communicate exclusively by sending messages according to a predefined interface scheme.The following interfaces are defined (in stub.cfg files for each class):

MovingHead Interface between BallTrackingHead and MovingHead2 for sending con-trol commands for moving AIBO’s head.

MovingLegs Interface between BallTrackingHead and MovingLegs2 for sending con-trol commands for moving AIBO’s legs.

LostFoundSound Interface between BallTrackingHead and LostFoundSound for sendingcontrol commands for playing sounds on the occurence of events.

FbkImageSensor Interface between BallTrackingHead and OVirtualRobot for retrievingthe image from AIBO’s camera view.

Sensor Interface between BallTrackingHead and OVirtualRobot for retrievinginformation from AIBO’s sensors (for computing the head-movementcommands for centering the focus).

Joint Interface between BallTrackingHead and OVirtualRobot for controllingthe position of head when focusing on the intruder or staff.

Move Interface between MovingLegs2 and OVirtualRobot for controlling thelegs.

Play Interface between LostFoundSound and OVirtualRobot for playing theWave files.

Move Interface between MovingHead2 and OVirtualRobot for controlling theposition of swinging head (Note: the OPEN-R allows to define twodifferent services with the same name).

82

Page 97: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.9. SYSTEM DESIGN

9.9.3 LEGO System

The state diagram in Figure 9.24 describes the functionality of the LEGO system. Initially,assuming the RCX is started by the On-Off and the Run button on the RCX, the factoryapplication is in a state waiting for a connection with the PC controller. In the states on the leftside of the figure, the cutting robot is operating, and the gate can be switched between unlockedand locked position dependant on the presence or absence of authorized staff. When the gateis unlocked, meaning that an authorized person has entered the entrance area, the gate can beopened by turning a wheel. If the gate is opened while the cutting robot is operating, the cuttingrobot is stopped, but will for safety reasons never start automatically when the gate closes. Thestates on the right correspond to cutting robot stopped, and again, the presence/absence ofauthorized staff results in unlocking/locking the gate. The transitions between the correspondingoperating and stopped states are executed either manually using On/Off buttons in the entrancearea outside the safety zone or remotely using the control window on the PC controller.

wait_start

stopped

stopped_staff running_staff

stopped_staff_in

running

START buttons & computer approves

Open gate Close gate

START buttons

STOP buttons

STOP buttons

“Staff” “No

staff” “No

staff” “Staff”

Open gate

“Intruder” “Intruder”

“No staff”

Note: all states have in addition a transition to a terminated state

Cutting robot running, gate locked

Cutting robot running, gate down and unlocked

Waiting for PC Gate locked

PC connected Cutting robot stopped Gate locked

PC connected Cutting robot stopped Gate down and unlocked

PC connected Cutting robot stopped Gate open and unlocked

Figure 9.24: State diagram: LEGO system

As Figure 9.25 shows, the Factory application consists of two separable modules: The post officecomponent and the factory controller. The interface between these two modules is based solely onthree calls of the Post Office API (see Section 9.10.3), after the PostOffice thread is started. Thefactory controller is implemented as a finite state automaton. The state transitions between thepossible states: wait start, stopped, stopped staff, stopped staff in, running, running staff, dis-connected trigger various actions, such as operating the actuators, or sending/receiving messagesto/from PC controller.

83

Page 98: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

Factory controller

Post Office

IR Port

Gate Engines

OFF BUTTON

ON BUTTON

SENSOR PORT 1

MOTOR A MOTOR C

SENSOR PORT 2

send_msg()

peek_msg() receive_msg() Ball3 /

PC

Figure 9.25: Factory application

9.9.4 PC Controller

The PC controller represents the link between the AIBO and the LEGO system. It is responsiblefor ordering the LEGO system to lock the gate when the AIBO detects an intruder and to stopthe cutting robot if AIBO becomes unavailable. Furthermore, authorized users shall be ableto control the cutting robot from the PC controller. Hence, a control window needs to beimplemented. The control window, which is illustrated in Figure 9.26, contains buttons forconnecting to AIBO, starting and stopping the cutting robot, and for shutting down the system(exit). The control window is updated with status information from both the AIBO and theLEGO system, such as announcements when the cutting robot is started or stopped, alertsabout intruder in the entrance area, and warnings about attempts to start the cutting robotwithout first connecting to the AIBO. As a special feature, which was introduced too late in thedevelopement process to be fully documented in this thesis, the control window shows the viewof AIBO, as well as a picture of its last detection, being a picture of either an authorized person(green LEGO man) or an intruder (pink ball).

84

Page 99: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.9. SYSTEM DESIGN

Figure 9.26: The control window on the PC controller

Figure 9.27 shows the state diagram for the overall functionality of the PC controller. Initially,assuming the Ball3 application is started, the PC Controller is in the state “Started” and thecontrol window is shown on the PC screen. From this state, possible transitions are to exit,which results in the state “Terminated”, or to connect to AIBO, which results in the state “AIBOconnected, Cutting robot inactive”. When AIBO is connected, the user (who is authorized byusing password protection on the control window) can start and stop the cutting robot eitherremotely through the control window, or manually by the On/Off buttons in the entrance area.The manually starting and stopping is shown in the diagram as the USER START MSG andUSER STOP MSG, respectively, as the PC Controller receives these messages from the LEGOsystem. If the connection to AIBO or to the LEGO system is lost, the PC Controller enters afatal state and sends stop signal to the LEGO system if possible, and transfers to the terminatedstate. The application can be terminated from all states by pressing the “Exit” button in thecontrol window, which results in stopping the cutting robot if it is operating.

85

Page 100: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

Started

Terminated

FATAL: Factory attempted to stop

AIBO connected, Cutting robot active AIBO connected, Cutting robot inactive Connect AIBO

Connection to LEGO system lost

Exit

Button STOP or USER_STOP_MSG received

Start button or USER_START_MSG received

Exit

AIBO connection lost / STOP_MESSAGE

Exit / STOP_MESSAGE

Exit

AIBO connection lost / STOP_MESSAGE Connection to LEGO

system lost

Figure 9.27: State diagram: PC Controller

The Ball3 application on the PC controller, illustrated in Figure 9.28, is the central componentlinking the AIBO and the LEGO system. It communicates with both and thus it has the mostcomplicated internal architecture. It consists of several classes and modules, and has severalthreads running independently.

LEGO factory

AIBO

Ball3

Wireless TCP/IP connection

Post Office GUI Thread

AIBO Thread

IR, LNP connection

Telnet log file Telnet

GUI Dialog

Figure 9.28: Component diagram: Ball3

The PostOffice component (implemented in Talking class) runs its own thread, which is respon-sible for the communication with the factory application of the LEGO system. After the Post

86

Page 101: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.9. SYSTEM DESIGN

Office thread is started, it periodically runs the external IR tool to retrieve new IR messages.Each time a message is being sent or received, it updates the semaphore-protected shared mem-ory (see Figure 9.29). The functionality of the post office component is described in Section9.10.3.

Waiting for start (PC) or first message (lego) Sleeping, waiting for confirmation msg

Updating data Waiting for semaphore

Waiting for IR tool to return msg or send

Releasing semaphore

Locking semaphore

Figure 9.29: State diagram: Post Office Thread

The GUI Thread periodically updates the GUI Dialog interface (the control window on the PCcontroller) with image views from the AIBO robot, as well as updating status information whenrequested by other modules (see Figure 9.30). The GUI Dialog (represented by the CBall3Dlgclass) receives user control commands entered through the control window, and takes an ap-propriate action (such as sending a start cutting request to the LEGO system or connecting toAIBO) based on the user request.

Waiting for start, gui_starting != 1 Sleeping Updating status information

Terminated

Gui_shutdown==1

Updating image view from AIBO

Figure 9.30: State diagram: GUI Thread

The AIBOThread (which is also a part of the Talking class) periodically loads the console log fileproduced by the telnet to detect all possible events occuring in AIBO: detecting the appearanceor disappearance of intruder or staff, interrupting the communication or shutting down AIBO(see Figure 9.31).

87

Page 102: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

Waiting for start, running != 1

Sleeping

Terminated shutdown

Intruder / BALL_FOUND_MESSAGE

aibo_connected

aibo_disconnected

shutdown

No_intruder / BALL_LOST_MESSAGE

Staff / STAFF_FOUND_MESSAGE

No_staff / STAFF_LOST_MESSAGE

Figure 9.31: State diagram: AIBO Thread

9.9.5 Collaboration Diagrams

Two specific examples of system operation are analyzed using collaboration diagrams.

Figure 9.32 shows a situation when an authorized person (green LEGO man) enters the entrancearea. First (1), an image from the camera in AIBO is sent through the fbkImageSensor interface(see below) from the OPEN-R’s OVirtualRobot, which provides an interface with the robot’shardware to the BallTrackingHead object of the application with the same name. This objectthen produces a STAFF FOUND event by printing to the telnet console (2). At the same timethe PictureSaver object running on the PC independently retrieves the image from the robot’scamera. When the Ball3 application detects the event in the telnet console log file, it (3) asksits GUIThread (see below) to display a status information to the user, and sends a message overthe IR link to the factory application of LEGO system, which in turn unlocks the gate (4).

BallTrackingHead Ball3 Factory

2:STAFF_FOUND 2:image

HW

1: image 3:STAFF_FOUND

3 : i m

a g

e s t

a t u

s

GUI

4:UNLOCK

GATE LOCK

Figure 9.32: Collaboration diagram: Green man

88

Page 103: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.9. SYSTEM DESIGN

Figure 9.33 shows the collaboration triggered by the user turning the gate-opening wheel. First(1), the wheel sensor changes the reading value, which is detected by the factory application onthe LEGO RCX. Next, the RCX turns the motor of the cutting robot off in order to stop thecutting robot (2), and then turns the gate motor on to open the gate completely (3), until thesensor indicates that the gate is open (4). As soon as the gate is successfully opened, a messageis sent (5) to the PC controller, which retrieves it and asks the GUIThread to display the statusinformation to the user (6).

Factory Ball3

Wheel

Gate motor

Gate sensor

GUI 3 : O p e n g a t e

4 : G a t e o p e n e d

1 : T u r n i n g w h e e l

5:GATE_OPEN STOPPED_CUTTING 6:Update status

Cutting robot motor 2 : S t o p c u t t i n g

Figure 9.33: Collaboration diagram: Gate open

89

Page 104: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

9.10 Implementation

This section describes the implementation of the prototype, which is step 6 of the developmentprocess (see Figure 9.34). The source code can be found in Appendix G.

Implementation 6

Testing and Safety validation 7

Concept 1

Overall Scope Definition 2

Preliminary Hazard Analysis 3

Design 5

I t e r a

t e (

m o

r e i

n f o

r m a

t i o n

/ d e

t a i l )

I t e r a

t e

Risk Management 4

Figure 9.34: Implementation

Figure 9.35 shows a picture of the prototype. The LEGO cutting robot can be seen at the backof the picture, placed inside the safety zone enclosed by lego walls. The lego gate is visiblethrough the entrance gateway into the safety zone, and two lights are placed above it. Theyellow light indicates that the cutting robot is operating, while the red light indicates that thegate is locked. In front of the entrance to the safety zone, the AIBO robot, representing themonitoring system, is placed to the

Figure 9.35: The factory

90

Page 105: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.10. IMPLEMENTATION

left while a green LEGO man, representing an authorized person, is placed to the right andinside the entrance area, which is the area in front of the AIBO, between the entrance and thelego wall in the front of the picture. The black and yellow box to the right of the entrance isthe on and off buttons for the cutting robot, and the wheel to the left of this box is the gatewheel for opening the gate. In the rightmost part of the picture the LEGO RCX and the IRtower (which is connected to the serial port of the PC controller) are located. The motors inthe cutting robot and the gate, as well as the touch sensors used for the On/Off buttons and fordetecting when the gate opens and close, are connected to the RCX through LEGO wires.

9.10.1 Choice of Programming Language and Development Environment

The implementation of the system includes programming of the Sony AIBO robot, the LEGOsystem (Lego Mindstorms cutting robot, gate, buttons and lights) and a controller applicationfor the PC.

The AIBO is programmed using the OPEN-R SDK version 1.1.3, which is a special operatingsystem developed by Sony. OPEN-R is briefly described in Section 6.3.1.

The implementation of the LEGO system is based on the implementation of the cutting robotdeveloped in the project “Risk assessment of Safety Critical Systems: An approach using LEGOMindstorms for prototyping” [28]. Thus, the programming language for the LEGO was initiallychosen to be LeJOS, which was the language used in that project. However, LeJOS is based onJava, which caused problems with the protocol for communication between the LEGO RCX andthe PC controller. The LeJOS API has good support for communication, but we experiencedconflicts with the control application running on the PC as this is written in C++. Therefore,the LEGO system is programmed in brickOS version 0.2.6, which is based on C and C++.

The application for the PC controller is programmed in C++, as a Windows 32-bit application,using Microsoft Visual C++ 6.0 (MSVC++ 6.0) and its Microsoft Foundation Classes (MFC).

9.10.2 AIBO Network Configuration and Settings

As described in Chapter 6.2, there are four types of wireless LAN network configurations. Inour system an access point is not used, thus the PC needs to be equipped with a wireless LANcard (see Figure 9.36). The AIBO and PC are set to IBSS Peer-to-Peer mode.

Figure 9.36: AIBO network configuration [20]

91

Page 106: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

For this type of network configuration, the settings for the PC are as follows:SSID: AIBONETWEP key: AIBO2Wireless channel: any channel between 1 and 11IP address: 10.0.1.101Subnet mask: 255.255.255.0Communication mode: IBSS Peer-to-Peer mode

AIBO’s network settings are as follows:

Item Description Default setting

Hostname The name of AIBO to be used forwireless LAN communication (up to8 alphanumeric characters).

AIBO

IP Address IP address 10.0.1.100

SubnetMask

Subnet mask value. 255.255.255.0

IP Gateway Gateway address. 10.0.1.1

SSID The name of the wireless LAN net-work to be used (up to 32 alphanu-meric characters).

AIBONET

WEP key The character string to be used asthe key for encrypting data trans-mitted over the wireless LAN (5 al-phanumeric characters).

AIBO2

Operatingmode

Infrastructure mode or ad hoc demomode

Since an accesspoint is not used,AIBO starts upin ad hoc demomode.

Wirelesschannel

When ad hoc demo mode is se-lected, select a number from 1 to 11for this item.

3

Table 9.19: AIBO network settings

92

Page 107: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.10. IMPLEMENTATION

9.10.3 The PO Protocol

The communication between the PC controller and the LEGO system is implemented using theinfrared (IR) technology for which is inherently unreliable. This section gives an overview of howthe challenge of achieving reliable and prompt communication is handled in our implementation.

The IR communication setup only allows to send asynchroneous packets, and the followingdifficulties can be identified:

• The communication link is unreliable: packets may be lost; an interference occurs if bothpeers start to send packets at the same time.

• The communication is not completely symmetrical: the LEGO RCX has a built-in IR portcontrolled by an LNP protocol that is part of the BrickOS system, whereas the PC needsan external device (IR tower) connected to a serial port. The IR tower can receive packetsonly while being active, and the LNP protocol on the PC side is only partially emulatedusing an external application (IR tool).

The security requirements imply that the status information and the control commands mustbe delivered reliably, instantly, and without blocking other functionality. Therefore, a reliablecommunication protocol, the Post Office protocol (PO protocol), has been developed for thecommunication over the unreliable IR communication link. The PO protocol is illustrated inFigure 9.37. The Postoffice figures in the figure represents the post office threads responsiblefor token passing. The PC figure represents all other threads of the Ball application running onthe PC and the lego figure represents the factory application. The boxes in the center depict IRpackets and the remaining boxes represent the PO variables. Access to the variables that areshared is protected by semaphores, denoted by sem.

The PO protocol is reliable, allows to send messages instantly, and runs in the background of themain application. It is based on passing tokens. The communicating peers A and B exchangetokens – usually empty messages in an alternating manner. Each message has a unique id, whichis determined by taking the id of the previous message and incrementing it by one. For instance,a message with id = 10 from A to B would be immediately followed by a message with id = 11from B to A, then immediately by a message with id = 12 from A to B, etc. After a maximumvalue is reached, the cycle restarts from the lowest possible value.

Each message represents a confirmation of the previous message, i.e. it is sent if, and only ifthe previous message was delivered successfully. Thus, only when the peer A receives a messagewith id = 11, can it be sure that the previous message with id = 10 was delivered successfully.Whenever the application requests the PO protocol to send a real message, the data of thatmessage are bundled with the next outgoing token.

The PO protocol is implemented on both platforms as a separate thread and runs independentlyof other functions of the application. This way it can deal with and report possible problemsin the communication link, and provide an asynchronous interface on the application side withmethods for sending and receiving messages, while keeping the synchroneous communication onthe IR side continuous. The API of the PO protocol consists of three self-explanatory calls:

int msg_send(char *msg);

int msg_receive(char *msg, int buffer_size);

int msg_peek();

93

Page 108: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Security-Safety Critical System

i

r i

r

i + 1

r i + 1

r

i + 2

r i + 2

r

j

r j

r

j+1

r j+1

r

k

r k

r

IR Post office Post office

A

B

A

sending

B

receiving

j id

j id B

received

to_send

sent PC PC lego lego

A

B

sem

A

received

to_send

sent

sem

B

A

B

sending

A

receiving

Post office Post office

order_nr

sending_nr

order_nr

j id

j id

sending_nr

Figure 9.37: The PO protocol

The msg send() call returns only if the message being sent was successfully sent and confirmed.The msg peek() call returns immediately, and the return value indicates the presence of areceived message in the buffer. If the PO protocol receives a message from the IR communicationlink, it saves it immediately to its internal buffer, and all consecutive calls to msg peek() willreturn 1, until the message is delivered when the application calls msg receive(). The functionmsg receive() is blocking, it returns the message in the receive buffer, if it is present. If themessage is not present, call to the function will wait until a new message is received.

The API functions communicate with the thread of the PO protocol by accessing shared variablesprotected by semaphores. For details on the implementation, the reader is referred to the moredetailed explanation of the PO protocol in Appendix E.

The PO protocol has been developed as an independent reusable component that providesreliable sending and receiving of messages over an unreliable IR communication link using LNP.Thanks to its buffering, it provides high throughput for asynchroneous communication, easy andtransparent API, guarantees delivery of messages in a correct order, but it does not implementmessage queues or priorities. Since it uses semaphores to access the data structures, it can besafely used in a multi-threaded application, where multiple threads can concurrently send andreceive messages. Possible extensions would allow addressing and crypting layers. However, thisis not implemented, but a subject to future work.

94

Page 109: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

9.11. TESTING AND SAFETY VALIDATION

9.11 Testing and Safety Validation

The last step of the development lifecycle is the testing and safety validation step, as illustratedby Figure 9.38. After this step, the process can be repeated, and it is iterated until the systemis regarded acceptable in terms of the safety and security requirements, as well as according tothe functional requirements.

Implementation 6

Testing and Safety validation 7

Concept 1

Overall Scope Definition 2

Preliminary Hazard Analysis 3

Design 5

I t e r

a t e

( m

o r e

i n f o

r m a

t i o n

/ d e

t a i l )

I t e r

a t e

Risk Management 4

Figure 9.38: Testing and Safety validation

The aim of the safety validation process is to prove that the system meets its safety requirements[24]. In our security-safety critical system, the validation of the security requirements servesmainly as an aid in the validation of the safety of the system. Risk analysis and testing are themain validation methods, and hence this step is performed stepwise and iteratively throughoutthe whole development process proposed in this work, and hence also for our prototype.

Testing comprises system testing, module testing and unit testing. Unit testing and moduletesting are generally performed in parallell with the implementation process, often by the de-veloper of the specific unit or module himself. After implementing and integrating the varioussystem modules, a system test can be carried out. This is executed on the complete system. Aplan for the system test is prepared on the basis of the functional requirements, and the test willshow whether the system fulfils these requirements. Due to time limitation we did no performthis step in this work. Further information on safety validation can be found in [24]. For testingfurther information can be found in [42].

95

Page 110: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

96

Page 111: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Chapter 10

Safety - Security

10.1 Introduction

In this chapter we discuss similarities, differences and dependencies between safety and security.We do so by describing how the two terms affect each other and by illustrating the importanceof being aware of the boundaries between the two. According to ISO/IEC 13335 ”Informationtechnology – Guidelines for management of IT Security” [38] security involves all aspects relatedto defining, achieving and maintaining confidentiality, integrity, availability, non-repudiation,accountability, authenticity and reliability, while ISO/IEC 17779 [39] only includes the firstthree properties. Leveson [46] defines safety as freedom from accidents and losses, and shedefines the difference between safety and security to be that safety relates to human life orharm to property, while security concerns national security or privacy. In order to clarify ourview we will start by discussing some of the definitions provided on security and safety, and tryto pinpoint the differences between the two. Further, we will describe the origin of the term“security-safety critical system” for which we denote systems where security and safety interactin order to fulfill the non-functional requirements of the system, being it a large productionsystem with industrial robots or an e-commerce application accessible from the Internet.

10.2 The Meaning of Safety and Security

The article “On the Meaning of Safety and Security” [14], written by A. Burns et al., aimsat giving a clearer understanding of the terms safety and security in order to produce betteranalysis techniques for dealing with safety and security. Safety and security are in this articledistinguished in terms of the nature of the harm caused and the nature of the casual relationshipsbetween events leading to a safety or security incident. A safety critical system is being definedas a system whose failure could do us immediate, direct harm, while a security critical systemas one that could enable, or increase the ability of, others to harm us. Thus, safety and securitycritical systems are those whose failure can lead, directly or indirectly, to harm.

According to IEC 61508 [34], which is a safety standard, harm denotes physical injury or damageto the health of people either directly or indirectly as a result of damage to property or to theenvironment. Safety is in this standard defined as freedom from unacceptable risk, where risk isthe combination of the probability of occurence of harm and the severity of that harm. Leveson[46] uses a similar definition on safety; freedom from accidents or losses, whereas Storey [61] hasdefined safety as “a property of a system that it will not endanger human life or the environment”.

97

Page 112: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Safety - Security

Security is by ISO 17799 [39], as mentioned in the introduction to this chapter, defined as thepreservation of confidentiality, integrity and availability. Likewise, ISO/IEC 13335 [38] definessecurity in terms of these, and four additional, security properties. Other definitions use avariety of combinations of the security properties, such as Pfleeger [54] and Stallings [58].

In the light of these definitions of safety and security, the statement made by Burns et al.about the distinguishing of safety and security in terms of their nature of harm caused and therelationships between initializing events seems valid. Breaches to one of the security attributes,and in particular to integrity and availability, can indirectly lead to harm if resulting in a systemfailure.

10.3 The Relationship between Safety and Security

Safety and security are closely related. Even though the existing definitions of security and safetyhave been developed separately, there are some conceptual similarities between the terms, whichmake it hard to distinguish between them. In some languages it is even impossible since the sameterm is used for both, such as Sicherheit in German and sikkerhet in Norwegian. Consequently,the distinction between safety and security is not always clear. The following sections addressthe similarities and differences between the two concepts, as well as their dependencies on eachother when combined in a security-safety critical system.

10.3.1 Similarities

Safety and security are similar in that they both include the concepts of threats and risk. Whilea threat as a safety issue is a threat to life or property, threats in a security context are toprivacy or national security. Safety and security are quality attributes related to future systemperformance. Both safety and security requirements differ from functional requirements in thatwe can never know if we have covered all risks, whereas we can test and verify that we havedelivered all required functionality. Both safety and security concern the protection againstlosses, and introduce the concept of safeguards or barriers. However, the barriers are in thesafety field used to prevent accidents, while they are used to prevent malicious incursions insecurity context [46].

Both safety and security are of great public concern. Hence, most safety-critical and security-critical systems are regulated by government agencies or licensing bureaus. Several standardsare specified for the purpose of controlling and guiding the development and operation of suchsystems.

10.3.2 Differences

While safety is concerned with consequences threatening the outside world, aiming at avoidinginjury of humans, security is concerned with data held within the computer system [36]. Secu-rity focuses on malicious actions, and the primary emphasis in security research has been theprevention of unauthorized access to classified information.

The article “Towards Operational Measures of Computer Security” Littlewood et al. [47], dis-cusses a quantitative approach towards modelling security by comparing traditional issues fromreliability theory and security. In the reliability context, the input space is the totality of allinputs to the system, representing all possible settings of sensors and controls. In the security

98

Page 113: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

10.4. SECURITY-SAFETY CRITICAL SYSTEMS

context the input space is represented by both all inputs to the system, both those involved innormal operational use and those which result from intentional attacks upon the system [47].The usage environment in reliability determines the mechanism by which the inputs will beselected from the input space. The analogy of usage environment in security is thus the popula-tion of attackers and their behaviours together with normal system operation. Despite the factthat ISO 13335 includes reliability as one of the security properties, we consider this propertyas being a safety property.

An alternative interpretation of reliability in relation with safety and security, is to define safetyand security as two reliability properties of a system. This approach is applied in the article“Safety and Security of Programmable Network Infrastructures” [2] by Alexander et al. A safesystem is here defined as a system that provides protection against errors of trusted users, whilea secure system protects against errors introduced by untrusted users.

10.3.3 Dependencies

When analysing a system according to its safety requirements, only the faults that have con-sequences for safety are considered. Other functional and non-functional requirements for thesystem are not of interest. However, in order to conduct a complete and accurate safety analy-sis, properties of the system environment must be considered, such as consequences of extremechanges in the environment, as well as consequences if the system fails to perform its intendedoperation. Hence, safety can only be assured by considering the safety-critical system as a whole,meaning that the software of the system must be included in the process. However, software initself is defined as not being able to directly cause an accident. The software component doesnot become safety-critical until it is used to control potentially dangerous systems. This situa-tion is what we have defined as security-safety critical. In a security-safety critical system, thesafety critical system is controlled by a security-critical control system, which generally includessoftware.

10.4 Security-Safety Critical Systems

Software is increasingly being used to control safety-critical systems, replacing the conventionaland nonprogrammable hardware control systems. Reasons for introducing computers to thecontrol of safety-critical systems vary. It can be in order to reduce costs, increase flexibilityfor design and future or prospective modifications, or to increase functionality. In some cases,digital computers may be required in order to meet certain requirements.

Computers are in particular used as part of or in some cases as the whole control or monitoringsystem. However, even though computerized systems in many cases increase the flexibility andensure more automated systems, it is not harmless. The use of software and digital computersincreases the complexity of a control system. Furthermore, vulnerabilities in computer systemsopens up for security breaches, which, if leading to failure in the control system, pose a threatto the safety of the safety-critical system. Based on this, we have chosen to introduce a newterm for the computer based safety-critical systems; security-safety critical systems. We havedone so in order to put particular emphasis on the relation between security threats and safetyconsequences.

99

Page 114: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Safety - Security

10.4.1 Introduction of Computers to Safety-Critical Control Systems

Challenges arise when introducing computers into safety-critical control systems. Often, thehosts and devices of a security-safety critical system are specialized embedded devices that arededicated to perform specific safety protecting functions. These devices often suffer from limitedprocessing power, and in many cases their operating system does not provide authentication,access control, fine-granularity file system protection and memory isolation between processes[49].

Furthermore, the control software is usually specially constructed for each application, as op-posed to conventional hardware control systems, which often use standard components producedin greater quantities. Application specific software has the advantage of adaptations and adjust-ments to the specific system. However, the lack of historical usage information makes it hard toestimate its reliability.

Due to the large number of states found in software, analysis of such a system for potentiallyunsafe behaviour can become extremely complex. Potential software failure modes are unpre-dictable and almost unlimited in number, as opposed to potential hardware failure modes, whichare generally predictable and limited in number [36]. Hence, when testing a software dependentcontrol system it can be difficult to provide realistic test conditions. Furthermore, testing mustoften be done in a simulation mode, which give no guarantee of accuracy of the real system.

10.4.2 Security Properties in a Safety Context

The security properties of security-safety critical systems differ from those in conventional,“office-type” IT systems. In the office-type systems, which are often connected with commer-cial and administrative data processing, security issues are related to security properties suchas confidentiality, integrity, authenticity and availability. While confidentiality and privacy areoften the most important requirements of an office IT system, they are often not even relevantfor security-safety critical systems, at least not in light of safety considerations.

The security attributes still have a meaning in security-safety critical systems. Confidentialityis relevant with respect to prevention of disclosure of passwords and encryption keys for thesecurity mechanisms, as well as domain specific information [49]. However, as safety is relatedto the injury of humans, or possibly to system failure, the safety is not affected by breaches ofconfidentiality. Loss of privacy is not regarded as a safety issue.

Integrity in a security-safety critical system refers to the prevention of unauthorized modificationof information transmitted both within the system and to and from its environment. This caninclude information such as control commands and sensor values, and hence a violation of thisattribute may cause safety consequences, that is, injury of people.

Availability in the context of security-safety critical systems refers to the assurance that all theIT elements of the system, such as control systems, safety critical systems, protection systemsand monitoring systems, are available. Safety consequences can result from the violation of thisattribute because the monitoring and protection mechanisms are inhibited.

Authenticity is concerned with determining if the person or program trying to interact withthe system are who they claim to be. If an unauthorized user is allowed to interact with thesecurity-safety critical system, false control commands may result in consequences for the safetyof the system.

100

Page 115: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

10.5. SAFETY CONSEQUENCES OF SECURITY THREATS

10.5 Safety Consequences of Security Threats

The Security-HazOp conducted in Chapter 9.5.1 identified security threats in connection withthe control system of the security-safety critical prototype system. Based on these threats,resulting hazards and their consequences for the safety of the system were identified. It wasdemonstrated that the vulnerabilities of the security-critical control system could have seriousimpact on the safety when combined with certain events. If alerts from the monitoring system,in this case a Sony AIBO robot, were lost on the way to the safety-critical system, which wasrepresented by a LEGO Mindstorms cutting robot in our prototype, the cutting robot wouldfail to stop when someone approached it. In a worst case scenario, this would lead to the deathof a person.

The degree of seriousness of the safety consequences depends on the security attribute involved,as well as the extent of the security violation.

Threats related to the confidentiality attribute, including disclosure of information to unautho-rized persons or systems, do not induce any safety consequences. It may involve the disclosureof sensitive information, thus threatening the privacy of people, or it may result in passwordsor encryption keys for the system being revealed. However, no harm is done to the people orequipment in the system. We say so because we only consider direct harm and not events thatmight open up for other harmful events.

The integrity attribute, however, is of great importance when it comes to the safety of a security-safety critical system. If assets in the system are manipulated, they can be prevented fromperforming their normal operation. Since most assets in such security-safety critical systems areresponsible for monitoring and protection of safety-critical assets, threats to integrity can resultin serious consequences for the safety of the system. Non-functioning protection mechansismscan result in people getting injured or in the worst case death.

If assets that are part of the control system of a security-safety critical system becomes unavail-able, the control system is inhibited. This is a security threat obviously related to the availabilityattribute. Generally, the control system is dependent on the correct operation of its componentsand their accurate communication and co-operation. If one or more of these components areunavailable, the control system will be prevented from performing its normal operation. Asnoted in the above paragraph, this may have serious consequences for the safety.

The consequences of threats to the authenticity attribute depend upon the manner of operation ofthe control system in the security-safety critical system. False messages can be inserted into thecommunication channels within the system, which in some cases can have consequences for thesafety, e.g. if a false start signal is sent to a potentially dangerous asset. Connecting the security-safety critical system to outside networks, such as the Internet, increases the vulnerability forthese types of threats. However, as discovered during the analysis conducted in this work, thesystem can in some cases be designed to reduce the extent of harm caused by such threats inthe communication channels. A good idea would be to keep logic and applications locally inthe various critical assets, if possible, in order to avoid unneccessary transmission of controlcommands through unreliable channels. Further, each critical asset should be able to determineif one or more of its connected “co-workers” are unavailable, and in that case be able to carryout the necessary action for this asset to contribute to safety assurance.

101

Page 116: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

102

Page 117: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Chapter 11

Conclusion and Further Work

In this thesis we have developed a prototype of a security-safety critical system, using LEGOMindstorms and Sony AIBO. The prototype was used as a means to study the relationshipbetween safety and security, and in particular safety concequences of security threats.

A development process for security-safety critical systems were proposed based on the safetylifecycle of the international safety standard IEC 61508 [33] and the CORAS integrated riskmanagement and system development process [11]. Further, some definitions from the safetyand security domain were redefined in order to adapt them to the security-safety domain andin order to be precise and concrete on the relationship between safety and security.

The development of the security-safety critical prototype followed the proposed developmentprocess: (1) The concept and (2) overall scope of the project were identified, resulting in a systemdescription and functional requirements, (3) A preliminary hazard analysis was applied to thesystem based on the system description and functional requirements, (4) Risk assessment wasperformed in order to identify security threats, evaluate their possible safety consequences andintroduce safeguards for not acceptable risks, (5) Designing the system, using UML diagrams,when no more unacceptable risks were identified (6) Implementing the system and (7) Testingand validating the system with emphasis on the safety requirements.

Due to time constraints, the last step of the proposed development process, (7) Testing andSafety validation, was not performed. Furthermore, simplifications and assumptions were appliedto the prototype. Suggestions for further work on the implementation are to apply strongerauthentication mechanisms such as smart cards on the PC controller, encryption of the messsagesover the wireless network, face recognition for the surveillance function in AIBO, and to extendthe system in order to allow more than one person inside the safety zone. Moreover, the proposedsecurity-safety development process needs to be applied to other systems in order to makeimprovements and extentions. It could also benefit from being tested on more complex systems,or even applied in a real world setting.

Experience about security-safety critical systems, gained during the development process, werefinally used in a discussion on the relationship between the terms safety and security, withparticular emphasis on the safety consequences of security threats. The security attribute “con-fidentiality” was found to be irrelevant in terms of safety. The “integrity”, “availability” and“authenticity” attributes, however, were identified to be indirectly related to the safety of asystem. Threats to one of these attributes may lead to system failure in the control system ofa security-safety critical system, and hence possibly also an accident.

103

Page 118: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

104

Page 119: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Appendix A

Glossary

Access point - a networking device with both wireless communication interface and telephoneline or Ethernet interface, which bridges across the wireless LAN and wired LAN [20].

Accident - an undesired and unplanned (but not necessarily unexpected) event that results in(at least) a specified level of loss [46].

Accountability - the property that ensures that the actions of an entity may be traced uniquelyto the entity [38].

Asset - anything that has value to the organization [38].(Major assets of computing systems: hardware, software and data.)

Authenticity - the property that ensures that the identity of a subject or resource is the oneclaimed [38].

Availability - the property that ensures that authorized users have access to information andassociated assets when required [39].

Confidentiality - the property that ensures that information is accessible only to those autho-rized to have access [39].

Control system - used to determine the operation of some form of equipment or plant [61].

New definition: Control system - used to monitor and protect a safety critical system.

Error - a deviation from the required operation of the system or subsystem [61].

Failure - termination of the ability of a functional unit to perform a required function [33].

105

Page 120: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Glossary

Fault - abnormal condition that may cause a reduction in, or loss of, the capability of a func-tional unit to perform a required function [33].

Harm - physical injury or damage to the health of people either directly or indirectly as a resultof damage to property or to the environment [33].

Hazard - a state or set of conditions of a system that, together with other conditions in theenvironment of the system, will lead to an accident [46].

Hazardous situation - circumstance in which a person is exposed to hazard(s) [33].

Hazardous event - hazardous situation which results in harm [33].

IBSS (Independent Basic Service Set) Peer-to-Peer mode - when you set at least onePC within the wireless LAN network to IBSS Peer-to-Peer mode, all devices within the networkcan communicate with each other without an access point [20].

Impact - the result of an unwanted incident [38].

Incident - an unintended event or sequence of events that does not result in loss, but, underdifferent circumstances, has the potential to do so [61].

Information security - preservation of confidentiality, integrity, availability, authenticity, re-liability, accountability and non-repudiation. (Derived from the definition of IT security in [?]

Information system - consists of people, machines and methods for collecting, processing,transmitting and disseminate data. (Derived from the definition of system in [46].)

Integrity - the property that safeguards the accuracy and completeness of information andprocessing methods [39].

Interlock mechanism - mechanism which ensures that potentially hazardous actions are onlyperformed at times when they are safe [61].

IT security policy - rules, directives and practices that govern how assets, including sensitiveinformation, are managed, protected and distributed within an organization and its IT systems[38].

IT system - the computerized part of the information system. (Derived from the definition ofsystem in [46].)

Loss - any negative consequence, financial or otherwise [4].

106

Page 121: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Monitoring system - monitoring part of a control system.

Non-repudiation - the property that ensures the ability to prove an action or event has takenplace, so that this event or action cannot be repudiated later [38].

Protection system - a system that uses sensors to detect fault conditions and produce outputsto mitigate their effects [61].

New definition: Protection system - protective part of a control system.

Reliability - the property of consistent intended behaviour and results [38].

Risk (security) - the potential that a given threat will exploit vulnerabilities of an asset orgroup of assets and thereby cause harm to the organization [38].

Risk (safety) - a combination of the likelihood of an accident and the severity of the potentialconsequences [46].

New definition: Risk - a combination of the likelihood of a security threat and the severity ofthe potential safety consequences.

Risk analysis - a systematic use of available information to determine how often specifiedevents may occur and the magnitude of their consequences [4].

Risk assessment - the overall process of risk analysis and risk evaluation [4].

Risk evaluation - the process used to determine risk management priorities by comparing thelevel of risk against predetermined standards, target risk levels or other criteria [4].

Risk identification - the process of determining what can happen, why and how [4].

Risk management - the culture, processes and structures that are directed towards the effec-tive management of potential opportunities and adverse effects [4].

Risk management process - the systematic application of management policies, proceduresand practices to the tasks of establishing the context, identifying, analyzing, evaluating, treat-ing, monitoring and communicating risk [4].

Risk treatment - selection and implementation of appropriate options for dealing with risk [4].

Safeguard - a practice, procedure or mechanism that reduces risk [38].

Safety - freedom from accidents or losses [46].- the property of a system that it will not endanger human life or the environment [61].

107

Page 122: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Glossary

Safety critical system - a system that by failing can cause harm to life, property or environ-ment [66].

Safety lifecycle - necessary activities involved in the implementation of safety-related systems,occurring during a period of time that starts at the concept phase of a project and finishes whenall of the E/E/PE safety-related systems, other technology safety-related systems and externalrisk reduction facilities are no longer available for use [33].

Safety requirements specification - specification containing all the requirements of the safetyfunctions that have to be performed by the safety-related system [33].

Security - See Information security.

Security critical system - a system whose assets contain vulnerabilities that might be ex-ploited.

Security-safety critical system - a system where a security critical system monitors andcontrols a safety critical system.

Stakeholder - an individual, team, or organization (or classes thereof) with interest in, or con-cerns relative to,a system [35].

System - a set of components that acts together as a whole to achieve some common goal,objective or end [46].

System environment - a set of components that is not part of the system but whose behaviorcan affect the system state [46].

Threat - a potential cause of an unwanted incident which may result in harm to a system ororganization [38].

New definition: Threat - a potential cause of an accident which may result in harm to a systemor organization.

Unwanted incident - Incident such as loss of confidentiality, integrity and/or availability [32]

Vulnerability - a weakness of an asset or group of assets which can be exploited by one ormore threats [38].

WEP (Wired Equivalent Privacy) - encrypts data tramsmit through the wireless LAN to preventtapping of information [20].

108

Page 123: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Appendix B

Abbreviations

DoS - Denial of Service

IEC - International Electrotechnical Commision

IP - Internet Protocol

IR - InfraRed

ISO - International Organization for Standardization

LAN - Local Area Network

OPEN-R - Open architecture for Robot entertainment

OSI - Open System Interconnection

PHA - Preliminary Hazard Analysis

PO - Post Office

RCX - Robotic Command eXplorer

RUP - Rational Unified Process

SSID - Service Set Identifiers

VPN - Virtual Private Network

WEP - Wired Equivalent Privacy

WLAN - Wireless Local Area Network

109

Page 124: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

110

Page 125: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Appendix C

Security-HazOp Tables

111

Page 126: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Secu

rity-H

azOp

Tab

les

Table C.1: Results of Security-HazOp - Breaches of confidentialityBreaches of Confidentiality

Expression Security threat Safety consequences Causes Countermeasures

Deliberate disclo-sure of informa-tion on AIBO

An unauthorized party getsaccess to the applicationcode of the AIBO

As long as the program is not al-tered, there is no consequences forthe safety

An unauthorized partygains access to the pro-grammable memory stick inAIBO

See to a secure storage ofthe memory stick when notin use

Deliberate disclo-sure of informa-tion in PC con-troller

An unauthorized party getsaccess to the applicationcode on the PC controller

Unauthorized copying of files andfolders, but no affect on the safetyas long as data are not altered.However, it opens up for breachesto integrity and authenticity

Missing or failing accesscontrol mechanism, or dis-closure of password

Access control mechanism,safe/secure password man-agement (generation andstorage) (strong authenti-cation, e.g. using smartcard in addition to pass-word)

An unauthorized party getsaccess to the control windowof the PC controller

Unauthorized user can control thefactory through the control win-dow. No effect on safety until in-formation is altered

Deliberate disclo-sure of messagesin the WLANcommunicationchannel

An unauthorized partygains access to the messagessent between AIBO and thePC controller

No consequence for the safety An unauthorized partyeavesdrops information onthe WLAN communicationchannel

Encryption mechanism

Deliberate disclo-sure of messagesin the IR commu-nication channel

An unauthorized partygains access to the IRsignals sent between the PCcontroller and the LEGOsystem

No consequence for the safety An unauthorized partyeavesdrops on the IRcommunication channel

Shielding of the IR com-munication channel

Deliberate disclo-sure of informa-tion in LEGO sys-tem

An unauthorized party getsaccess to the applicationcode on the LEGO RCX

As long as the program is not al-tered, there is no consequences forsafety

An unauthorized partygains access to the ap-plication on the LEGORCX

Shielding of the RCX

112

Page 127: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Table C.2: Results of Security HazOp - Breaches of integrityBreaches of Integrity

Expression Security threat Consequences Causes Countermeasures

Deliberate manip-ulation of AIBO

AIBO is manipulated to ig-nore “intruders” or to notsend alerts when detecting“intruders”

The PC controller, and then againthe LEGO system, is not notifiedwhen an intruder enters the en-trance area, thus the gate fails toclose and the intruder can enterthe safety zone, which can lead topossible injury of a person

An unauthorized partygains access to the pro-grammable memory stickin AIBO and manipu-lates/modifies the applica-tion program

See to a secure storage ofthe memory stick when notin use. Shielding of AI-BOs lower part in order toprevent easy access to thememory stick

AIBO is manipulated to ig-nore persons entering thesafety zone or to not sendalerts when detecting per-son entering the safety zone

The PC controller, and then againthe LEGO system, is not notifiedwhen a person enters the safetyzone, thus the cutting robot failsto stop. Possible death or injuryof person

Deliberate manip-ulation of PC con-troller

PC controller is manipu-lated to ignore “intruderalert” or to not send “closegate” signal when receiving“intruder alert” from AIBO

The LEGO system is not notifiedwhen an intruder enters the en-trance area, thus the gate fails toclose and the intruder can enterthe safety zone, which can lead topossible injury of a person

An unauthorized partygains access to the ap-plication code on the PCcontroller and manipu-lates/modifies it

Extend access controlmechanism (strong au-thentication) and writeprotected files

PC controller is manipu-lated to ignore “enteredsafety zone” signals or tonot send stop signal toLEGO system when receiv-ing an “entered safety zone”signal from AIBO

The LEGO system is not notifiedwhen a person enters the safetyzone, thus the cutting robot failsto stop. Possible death or injuryof person

Deliberate manip-ulation of LEGOsystem

The LEGO system is manip-ulated to ignore stop signalsfrom the PC controller

The cutting robot fails to stopwhen a person enters the safetyzone. Possible death or injury ofa person

An unauthorized partygains access to the applica-tion of the LEGO RCX andmanipulates it

??

The LEGO system is manip-ulated to never stop the cut-ting robot

113

Page 128: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Secu

rity-H

azOp

Tab

les

Table C.3: Results of Security HazOp - Breaches of integrity cont.Breaches of Integrity - cont.

Expression Security threat Consequences Causes Countermeasures

Deliberate ma-nipulation ofmessages in theWLAN communi-cation channel

An “intruder alert” is mod-ified to a “regular” message

The gate fails to close when anintruder enters the entrance area.The intruder can then enter thesafety zone

The receiver on the PC con-troller is blocked while an-other receiver receives thetransmitted message andmodifies its content beforeunblocking and forwardingthe modified message to thePC controller

Encryption of transmittedmessages over the WLAN,shielding of the WLANcommunication channel,and use of timestamps

An “entered safety zone”signal is modified to a “reg-ular” message

The cutting robot fails to stopwhen a person enters the safetyzone. Possible death or injury ofperson

An “entered safety zone”signal is modified to an “in-truder alert”

The gate closes instead of robotstopping. Because of time delay,the person may be able to enterbefore the gate is closed. Possibledeath or injury of person

Deliberate ma-nipulation ofmessages in theIR communica-tion channel

A stop signal is modified toa start signal

The cutting robot fails to stopwhen a person enters the safetyzone. Possible death or injury ofperson

The IR receiver on the RCXis blocked while another re-ceiver receives the transmit-ted message and modifies itbefore unblocking the RCXand forwarding the modifiedmessage

Shielding of the IR com-munication link

A “close gate” signal is mod-ified to a stop or start signal

The gate fails to close when anintruder enters the entrance areaand the intruder can then enterthe safety zone

114

Page 129: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Table C.4: Results of Security-HazOp - Breaches of availabilityBreaches of Availability

Expression Security threat Consequences Causes Countermeasures

Deliberate denialof alerts/messagesfrom AIBO

AIBO is prevented from de-tecting intruder in the en-trance area, or person enter-ing the safety zone

The monitoring part of the sys-tem is unavailable. The gate willnever close, and the cutting robotwill not stop if someone enters thesafety zone. Possible death or in-jury of person

Sabotage, AIBO is shutdown, Denial of Service at-tack, AIBO is stolen/moved

Shut down system/stopcutting robot if AIBOis unavailable/connectionlost

AIBO is prevented fromsending messages to the PCcontroller

Unintentionaldenial ofalerst/messagesfrom AIBO

AIBO is prevented from de-tecting intruder in the en-trance area, or person enter-ing the safety zone

The monitoring part of the sys-tem is unavailable. The gate willnever close, and the cutting robotwill not stop if someone enters thesafety zone. Possible death or in-jury of person

Natural disaster, AIBO hasbeen shut down acciden-tally because of low batterypower

Shut down system/stopcutting robot if AIBO isunavailable or connectionis lost

AIBO is prevented fromsending messages to the PCcontroller

Deliberate delayof alerts/messagesfrom AIBO

PC controller receives thealert messages from AIBOtoo late

The gate may close too late, andthe cutting robot may stop toolate if someone enters the safetyzone. Possible death or injury ofperson

Denial of Service attack Timestamp, alive time,and message number withalert message is “messageis out of sequence”

Unintentionaldelay ofalerts/messagesfrom AIBO

PC controller receives thealert messages from AIBOtoo late

The gate may close too late, andthe cutting robot may stop toolate if someone enters the safetyzone. Possible death or injury ofperson

Technical failure

Deliberate denialor delay of mes-sages from PCcontroller

The PC controller is un-available/prevented fromperforming its normaloperation

The linking between AIBO andthe LEGO system is broken. Thegate will never close or closes toolate, and the cutting robot willnot stop or stops too late if some-one enters the safety zone. Possi-ble death or injury of person

Sabotage, power shutdown,PC is shut down, Denial ofService

Shut down system/stopcutting robot if connectionis lost (timeout)

Unintentional de-nial or delay ofmessages from PCcontroller

The PC controller is un-available/prevented fromperforming its normaloperation

The linking between AIBO andthe LEGO system is broken. Thegate will never close or closes toolate, and the cutting robot willnot stop or stops too late if some-one enters the safety zone. Possi-ble death or injury of person

Natural disaster, technicalfailure

Shut down system/stopcutting robot if connectionis lost (timeout)

115

Page 130: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Secu

rity-H

azOp

Tab

les

Table C.5: Results of Security-HazOp - Breaches of availability cont.Breaches of Availability - cont.

Expression Security threat Consequences Causes Countermeasures

Deliberate de-nial or delay ofmessages in theLEGO system

Actions are not carried outor are carried out too late inthe LEGO system

The LEGO system is unavailable.The gate will not close or close toolate, and the cutting robot willnot stop or stop too late. Possi-ble death or injury of a person

Sabotage, Denial of Service

Unintentional de-nial or delay ofmessages in theLEGO system

Actions are not carried outor are carried out too late inthe LEGO system

The LEGO system is unavailable.The gate will not close or close toolate, and the cutting robot willnot stop or stop too late. Possi-ble death or injury of a person

Low battery level in theLEGO RCX, natural disas-ter

Deliberate de-nial/delay ofmessages in theWLAN communi-cation channel

An “intruder alert” fromAIBO to the PC controlleris lost or delayed

The gate is not closed or closes toolate when an intruder enters theentrance area. Possible injury ofperson

Interruption of sig-nals/Interference of radiosignals by other senders/Transmitted data destroyedby other electrical device

Shielding of the wirelesscommunication link

An “entered safety zone”signal from AIBO to the PCcontroller is lost or delayed

The cutting robot is not stoppedor stops too late when a personenters the safety zone. Possibledeath or injury of person

Errors in configuration set-tings of network or modifiednetwork settings, WLANcard removed from PC orAIBO

Direct communication be-ween AIBO and LEGOsystem,

The communication link be-comes unavailable

The gate is not closed when anintruder enters the entrance areaand the cutting robot is notstopped when a person enters thesafety zone. Possible death or in-jury of person

Frequent control signalsfrom AIBO - control sys-tem should shut down sys-tem if control signal is lost)

Deliberate de-nial/delay ofmessages in theIR communica-tion channel

A “close gate” signal fromthe PC controller is lost ordelayed

The gate is not closed or closes toolate when an intruder enters theentrance area. The intruder canthen enter the safety zone, whichcan lead to injury.

Physical blocking of IR sig-nals

Shielding of the IR com-munication link

A stop signal from the PCcontroller is lost or delayed

The robot is not stopped or stopstoo late when a person enters thesafety zone. Possible death or in-jury of person

116

Page 131: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Table C.6: Results of Security-HazOp - Breaches of authenticityBreaches of Authenticity

Expression Security threat Consequences Causes Countermeasures

Deliberatefabrica-tion/masqueradeof AIBO

Unauthorizeduser/component acts asAIBO and fabricates mes-sages

Masquerade AIBO sends messagethat staff or intruder is not inentrance area or safety zone anylonger when they still are present,which can lead to possible deathor injury

Masquerade AIBO (falseAIBO) has taken over therole of the real AIBO

Implement authenticationmechanism between AIBOand PC controller

Deliberatefabrica-tion/masqueradeof PC controller

Unauthorizeduser/component acts asPC controller and fabricatesmessages

PC controller sends start messageto LEGO system while someone isin the safety zone, which can leadto possible death or injury

Masquerade PC controller(false PC controller) hastaken over the role of thereal PC controller

Implement authenticationmechanism between PCcontroller and LEGO sys-tem

Deliberatefabrica-tion/masqueradeof messages in theWLAN communi-cation channel

A false “intruder alert” is in-serted into the wireless LAN

The PC controller assumes thatan intruder has entered the en-trance area, and sends a “closegate” signal to the LEGO system.The gate is closed needlessly, butno effect on safety

Not considered because itdoes not affect the safety ofthe system

A false “entered safetyzone” signal is inserted intothe wireless LAN

The PC controller assumes thata person has entered the safetyzone, and sends a stop signal tothe LEGO system. The cuttingrobot is stopped needlessly, butno effect on safety

A false “disconnect” signalfor AIBO is inserted into thewireless LAN

AIBO becomes unavailable (formore information see Table C.4 inAppendix C)

Not considered because itdoes not affect the safety ofthe system

Deliberatefabrica-tion/masqueradeof messages in theIR communica-tion channel

A false stop signal is in-serted into the IR commu-nication channel

The cutting robot is stoppedneedlessly, but no effect on safety

An unauthorized party mas-querades as the PC con-troller and sends spuriousmessages to the LEGO sys-tem

Shielding of the IR com-munication channel

A false “close gate” signal isinserted into the IR commu-nication channel

The gate is closed needlessly, butno effect on safety

A false start signal is in-serted into the IR commu-nication channel

The cutting robot may be startetwhen a person is inside the safetyzone. Possible death or injury ofperson

Prevent start from controlwindow

117

Page 132: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

118

Page 133: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Appendix D

Risk Analysis Tables

119

Page 134: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Risk

Analy

sisTab

les

Table D.1: Analyse Risk - Breaches of confidentialityBreaches of ConfidentialitySecurity threat Safety consequences Consequence

valueLikelihoodvalue

Classification

An unauthorized party gets ac-cess to the application code on theAIBO.

As long as the program is not al-tered, there is no consequences forthe safety.

Negligible Improbable IV

An unauthorized party gets accessto the application code on the PCcontroller.

Unauthorized copying of files andfolders, but no affect on the safety aslong as data are not altered. How-ever, it opens up for breaches to in-tegrity and authenticity.

Negligible Occasional IV

An unauthorized party gets accessto the control window of the PCcontroller.

Unauthorized user can control thefactory through the control window.No affect on safety until informationis altered.

Negligible Probable IV

An unauthorized party gains accessto the messages sent between AIBOand the PC controller.

No consequence for the safety. Negligible Occasional IV

Unauthorized party gains access tothe IR signals sent between the PCcontroller and the LEGO system.

No consequence for the safety. Negligible Occasional IV

An unauthorized party gets ac-cess to the application code on theLEGO RCX

As long as the program is not al-tered there is no consequences forthe safety.

Negligible Remote IV

120

Page 135: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Table D.2: Analyse Risk - Breaches of integrityBreaches of IntegritySecurity threat Safety consequences Consequence

valueLikelihoodvalue

Classification

AIBO is manipulated to ignore “in-truders” or to not send alerts whendetecting “intruders”.

The PC controller, and then againthe LEGO system, is not notifiedwhen an intruder enters the en-trance area, thus the gate fails toclose and the intruder can enter thesafety zone, which can lead to pos-sible injury of a person

Catastrophic Improbable III

AIBO is manipulated to ignore per-sons entering the safety zone or tonot send alerts when detecting per-son entering the safety zone.

The PC controller, and then againthe LEGO system, is not notifiedwhen a person enters the safetyzone, thus the cutting robot fails tostop. Possible death or injury ofperson.

Catastrophic Improbable III

PC controller is manipulated to ig-nore “intruder alert” or to not send“close gate” signal when receiving“intruder alert” from AIBO.

The LEGO system is not notifiedwhen an intruder enters the en-trance area, thus the gate fails toclose and the intruder can then en-ter the safety zone, which can leadto possible injury of a person.

Critical Occasional II

PC controller is manipulated to ig-nore “entered safety zone” signalsor to not send stop signal to LEGOsystem when receiving an “enteredsafety zone” signal from AIBO.

The LEGO system is not notifiedwhen a person enters the safetyzone, thus the cutting robot fails tostop. Possible death or injury ofperson.

Catastrophic Occasional I

The LEGO system is manipulatedto ignore stop signals from the PCcontroller.

The cutting robot fails to stop whena person enters the safety zone. Pos-sible death or injury of a person

Catastrophic Incredible IV

The LEGO system is manipulatedto never stop the cutting robot.

The cutting robot fails to stop whena person enters the safety zone. Pos-sible death or injury of a person

Catastrophic Incredible IV

121

Page 136: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Risk

Analy

sisTab

les

Table D.3: Analyse Risk - Breaches of integrity cont.Breaches of Integrity cont.Security threat Safety consequences Consequence

valueLikelihoodvalue

Classification

An “intruder alert” is modified to a“regular” message.

The gate fails to close when an in-truder enters the entrance area. Theintruder can then enter the safetyzone, which can lead to injury.

Critical Improbable III

An “entered safety zone” signal ismodified to a “regular” message.

The cutting robot fails to stop whena person enters the safety zone. Pos-sible death or injury of person.

Catastrophic Improbable III

An “entered safety zone” signal ismodified to an “intruder alert”.

The gate closes instead of robotstopping. Because of time delay, theperson may be able to enter beforethe gate is closed. Possible death orinjury of person.

Catastrophic Improbable III

A stop signal is modified to a startsignal.

The cutting robot fails to stop whena person enters the safety zone. Pos-sible death or injury of person.

Catastrophic Remote II

A “close gate” signal is modified toa stop or start signal.

The gate fails to close when anintruder enters the entrance areaand the intruder can then enter thesafety zone, which can lead to in-jury.

Critical Remote III

122

Page 137: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Table D.4: Analyse Risk - Breaches of availabilityBreaches of AvailabilitySecurity threat Safety consequences Consequence

valueLikelihoodvalue

Classification

AIBO is prevented from detectingintruder in the entrance area, orperson entering the safety zone.

The monitoring part of the systemis unavailable. The gate will neverclose, and the cutting robot will not

Catastrophic Probable I

AIBO is prevented from sendingmessages to the PC controller.

stop if someone enters the safetyzone. Possible death or injury ofperson.

PC controller receives the alert mes-sage from AIBO too late.

The gate may close too late, andthe cutting robot may stop toolate when someone enters the safetyzone. Possible death or injury ofperson.

Catastrophic Occasional I

The PC controller is unavail-able/prevented from performing itsnormal operation.

The linking between AIBO and theLEGO system is broken. The gatewill never close or closes too late,and the cutting robot will not stopor stops too late when someone en-ters the safety zone. Possible deathor injury of person.

Catastrophic Frequent I

Actions are not carried out or arecarried out too late in the LEGOsystem.

The LEGO system is unavailable.The gate will not close or close toolate and the cutting robot will notstop or stop too late. Possible deathor injury of a person.

Catastrophic Probable I

123

Page 138: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Risk

Analy

sisTab

les

Table D.5: Analyse Risk - Breaches of availability cont.Breaches of Availability cont.Security threat Safety consequences Consequence

valueLikelihoodvalue

Classification

An “intruder alert” from AIBO tothe PC controller is lost or delayed.

The gate is not closed or closes toolate when an intruder enters the en-trance area. Possible injury of per-son.

Critical Probable I

An “entered safety zone” signalfrom AIBO to the PC controller islost or delayed.

The cutting robot is not stopped orstops too late when a person entersthe safety zone. Possible death orinjury of person.

Catastrophic Probable I

The (WLAN) communication linkbecomes unavailable.

The gate is not closed when an in-truder enters the entrance area andthe cutting robot is not stoppedwhen a person enters the safetyzone. Possible death or injury ofperson.

Catastrophic Probable I

A “close gate” signal from the PC islost or delayed.

The gate is not closed or closes toolate when an intruder enters the en-trance area. The intruder can thenenter the safety zone, which can leadto injury.

Critical Frequent I

A stop signal from the PC controlleris lost or delayed.

The robot is not stopped or stopstoo late when a person enters thesafety zone. Possible death or injuryof person

Catastrophic Frequent I

124

Page 139: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Table D.6: Analyse Risk - Breaches of authenticityBreaches of AuthenticitySecurity threat Safety consequences Consequence

valueLikelihoodvalue

Classification

Unauthorized user/component actsas AIBO and fabricates messages.

Masquerade AIBO sends messagethat staff or intruder is not in en-trance area or safety zone any longerwhen they still are present, whichcan lead to possible death or injury.

Catastrophic Remote II

Unauthorized user/component actsas PC controller and fabricates mes-sages.

PC controller sends start message toLEGO system while someone is inthe safety zone, which can lead topossible death or injury.

Catastrophic Remote II

A false “intruder alert” is insertedinto the wireless LAN.

The PC controller assumes that anintruder has entered the entrancearea, and sends a “close gate” sig-nal to the LEGO system. The gateis closed needlessly, but no effect onsafety.

Negligible Remote IV

A false “entered safety zone” signalis inserted into the wireless LAN.

The PC controller assumes that aperson has entered the safety zone,and sends a stop signal to theLEGO system. The cutting robotis stopped needlessly, but no effecton safety.

Negligible Remote IV

A false “disconnect” signal forAIBO is inserted into the wirelessLAN.

AIBO becomes unavailable (formore information see Table C.4 inAppendix C)

A false stop signal is inserted intothe IR communication channel.

The cutting robot is stopped need-lessly, but no effect on safety

Negligible Occasional IV

A false “close gate” signal is insertedinto the IR communication channel.

The gate is closed needlessly, but noeffect on safety

Negligible Occasional IV

A false start signal is inserted intothe IR communication channel.

The cutting robot may be startetwhen a person is inside the safetyzone. Possible death or injury ofperson

Catastrophic Occasional I

125

Page 140: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

126

Page 141: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Appendix E

Post office - detailed description

The legOS development platform offers a simple network protocol LNP (layered network proto-col, sometimes also referred to as LegOS Network Protocol ) [3]. LNP (which is seated in theNetwork layer) implements simple packet sending/receiving methods with checksum verificationand possible addressing features. Still, the protocol does not guarantee that the message willbe delivered, and it is asynchronous thus containing no prevention of possible conflicts. On thePC side, a partial emulator of the protocol is implemented in form of an external utility (IRtool). The emulator is only partial, because the message delivery cannot occur passively as onthe legOS side, but the IR tool must be executed in order to start receiving a message (this isa second complication in addition to the limitation of the IR tower that it needs to be lit toreceive messages). Similarly, the IR tool must be executed for each message sent out. For adetailed usage of the IR tool, see Figure E.1.

The PO protocol, as described in Section 9.10.3, is based on passing tokens with incrementing ids,and provides easy API with the 3 functions msg send(), msg receive(), and msg peek(). Thesefunctions communicate with the thread of the PO protocol by accessing the shared variablesshown below. The exclusive access is guaranteed by the use of POSIX semaphores (on Win32platform they are emulated using Windows semaphores).

char *to_send;

int order_nr;

int sent;

char received[MAX_MSG_LENGTH];

The variable to send stores a pointer to the next packet prepared to be sent. Whenever it isnonzero, the packet pointed to must be fetched by the PO thread(?) before the msg send()function can store a pointer to a new packet to be sent. As soon as the PO fetches the packetwaiting to be sent, it clears (sets to zero) the to send variable to indicate that it is allowed fora new packet to enter the sending buffer to send. When msg send() sets the to send pointer,it also retrieves its order number from (order nr) variable. After the PO successfully managesto send this packet, it will set the sent variable to the corresponding order nr to indicate thatthe message was sent and confirmed successfully. Thus the msg send() function only needs towait until sent becomes equal to the proper order number:

msg_send(char *A)

127

Page 142: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Post office - detailed description

IR send <port> <message_file>

IR receive <port> <message_file> <timeout> [wakeuptower]

where <port> is the serial communication port: COM1, COM2...

<message_file> is the name of the file from which the

message to be sent is read, or to which the received

message is saved

<timeout> is the time in milliseconds that the IR tool

is waiting to receive a message

wakeuptower option specifies that the tower ought to

be lit before trying to receive a message; this is

achieved by sending a single byte 0.

For example, the command:

IR send com1 outgoing.txt

will send a packet consisting of the string found in the

file outgoing.txt on the first line, and the command:

IR receive com1 in.txt 1000 wakeuptower

will try to receive any message, and if it will arrive

within 1 second, it will be saved into the file in.txt

Figure E.1: Detailed usage of IR tool

{

function uses one local variable order_nr_A

1. wait until to_send becomes zero, use the PO semaphore when

accessing the variable

2. if timeout occured and to_send is still nonzero, unlock

semaphore and return 0

3. semaphore is now locked, and to_send is zero, so:

set to_send to A, take order_nr_A = order_nr, and unlock

the semaphore

4. wait until sent != order_nr_A, use the PO semaphore when

accessing the variable

5. if timeout occured and sent is still != order_nr_A, unlock

semaphore and return 0

6. semaphore is now locked and sent == order_nr_A, i.e.

message delivery is confirmed, set sent = 0, unlock the

semaphore and return 1

}

The variable received[] always contains a copy of the last packet that arrived, or an empty stringif no packet has arrived. The msg receive() function is responsible for setting this variable toan empty string after it have taken a copy of the stored packet, so that a new packet can bereceived. In order to avoid complete locking of the application, the function always returns after

128

Page 143: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

a timeout, even if the message is not received. The msg peek() call simply returns the lengthof the received[] string, thus returning 0 if no new message arrived.

msg_receive(char *B, int buffer_size)

{

1. wait until received[0] != ’\0’, use semaphore when

accessing the variable

2. if timeout occured, unlock semaphore and return 0

3. semaphore is now locked, received[0] != ’\0’,

copy received to B, if it does not exceed the buffer size

set received[0] to ’\0’

4. unlock semaphore and return the length of B

}

msg_peek()

{

1. lock semaphore

2. get strlen(received) to ln

3. unlock semaphore

4. return ln

}

The thread employs the LNP to listen for the incoming message and receive it as soon asit arrives. Then it prepares a new message to be sent. Each message consists of an id,ready to receive status flag, and an optional message string, which can be empty. When anew packet is prepared, i.e. the to send is nonzero, the packet is copied to the variable sending,and it is sent with the next message (see Figure 9.37). A message is always sent tmsg interval

milliseconds after the last message arrived. The message is kept in the sending variable untilit is successfully confirmed, i.e. until the next message arrives. The other data structures arethen updated correspondingly to comply with the protocol described above. A received packetis immediately copied into the receiving buffer variable, where it waits until the received buffervariable is clean (i.e. zero) and ready to hold the newly received packet. The double-buffer isused to support smooth link between asynchroneous communication on the PO API side andsynchroneous communication on the IR side. On the other hand, if both the received and re-ceiving buffers are full, the PO indicates that it is unable to receive more messages from thecommunicating peer by setting the ready to receive flag in the next outgoing message to 0, andthen it ignores all packets received in the forthcoming messages, unless the buffer is cleaned bymsg receive(). However, even if the receive buffers are full, it is still possible to reliably sendmessages to the other communicating peer, since the token passing is not interrupted.

A couple of issues when using the PO protocol on the PC controller side include: Settingup the serial communication port parameters is required, and certain limitations occur. Forinstance, it is not recommended to send the ESC character (ASCII code 26) as it triggers anESC control sequence (in general, many characters with ASCII codes below 32 (SPACE) modifythe communication to such an extent that it becomes less reliable).

In the actual implementation, the range of possible values for the id of a message is limited to[32; 127] for the reasons described above, and to ensure compatibility with 7-bit transmission.

The functionality of the PO thread is demonstrated with an example illustrated in the POsequence diagram in Figure E.2. The diagram shows the details of data exchange in an example

129

Page 144: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Post office - detailed description

when a message is sent from the factory application running on the RCX to the Ball applicationrunning on the PC. The POInterface timelines represent the semaphore-protected memory areasshared between the PO thread and the application calls to PO API. The communication betweenthe two IRThreads is performed by sending and receiving IR packets using LNP protocol. Thereceiving side (PC) calls the msg peek() twice: the first call informs that the buffer is empty.The second call informs that the message is ready. A consequent call to msg receive() retrievesthe received message from the buffer.

sent != order_nr

main msg_send

msg_send("U")

PO interface IRThread PO interface : Talking IRThread msg_peek : Talking AiboThread

Lego sends message USER_START_MESSAGE to PC

to_send == 0

to_send = "U"

order_nr U

copy to_send to sending

copy order_nr to sending_nr

to_send = 0

order_nr++

i, 1, U

return 1

received == 0

copy receiving to received peek_msg()

received == 0

msg_peek()

return 0

receive_msg()

return 1

received != 0

copy received

received = 0

return ("U")

i+1, 1

sent = sending_nr

sent == order_nr

S E

N D

_ M S

G _ I

N T

E R

V A

L

X t i

m e s

Lock semaphore

Unlock semaphore

Lock semaphore

Unlock semaphore

Unlock semaphore

Lock semaphore

u

u

Lock semaphore

Unlock semaphore

Lock semaphore

Unlock semaphore

Lock semaphore

Unlock semaphore

Unlock semaphore

Unlock semaphore

Unlock semaphore

Lock semaphore

Lock semaphore

Lock semaphore

msg_receive : Talking

PC

LEGO RCX Factory

Figure E.2: Sequence diagram: Functionality of the PO (Post Office) thread

130

Page 145: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Appendix F

Operating Manual

Commands for starting the system:

I RCX

1. Boot Linux operating system with LegOS 0.2.6 installed (to install, follow the instal-lation instructions in the documentation published at http://legos.sourceforge.net/the installation package is included on the CD).

2. Enter legOS directory (e.g. cd /usr/local/legOS).

3. Make sure the IR tower is connected to a serial port (e.g. COM1), and has a operating9V battery installed. Make sure that there is a free optical connection between theIR tower and the IR port of the RCX, and the IR tower is placed ca. 20 cm awayfrom the RCX.

4. Power on the RCX using the red ON/OFF button.

5. Download the LegOS firmware to RCX using the command: util/firmdl3 boot/legOS.srec

6. (optionally) Build the lx-file (binary) for the factory in the LegOS demo directory bytyping make (and make sure that the factory.lx is mentioned in the list of files to bebuilt in the demo\Makefile)

7. Download the factory program to RCX with the following command from the legOSdirectory: util/dll demo/factory.lx

8. Start the program on RCX by pressing the green RUN button. The RCX displayshould show a ”READY” message on its LCD.

II AIBO

1. Prepare the memory stick by copying the BallTrackingHead2/OPEN-R directory tothe memory stick’s root directory. (Optionally: first, compile the application bytyping make;make install in the BallTrackingHead2 directory that was placed underthe sample directory in the OPEN-R distribution - provided cygwin and OPEN-Rare installed on the PC).

2. Insert the memory stick to Aibo.

3. Make sure the wireless network cards are inserted and properly configured for AIBOnetwork settings.

131

Page 146: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Operating Manual

4. In a separate cygwin shell window, start ipc deamon (an application that is part of theRemote Processing OPEN-R, and that implements the UNIX-like interprocess comu-nication in Windows environment). Issue the following command: /usr/local/bin/ipc daemonThis step needs to be executed only once per reboot.

5. Execute the PictureSaver application by starting the Remote Processing OPEN-R:From a new cygwin shell, type: cd samplePrograms/sample/BallTrackingHead2/RP/host/usr/local/OPEN-R-SDK/RP-OPEN-R/bin/start-rp-openr

(Optionally: first, build the PictureSaver application by typing make;make install inthe samplePrograms/sample/BallTrackingHead2 directory)

6. Boot Aibo, wait until it is ready and starts moving its head.

III PC

1. Start the main application by executing the program ball3.exe. (Optionally: Firstbuild the application using MSVC++ 6.0 from the sources; the workspace and projectfiles are provided).

2. Connect to Aibo by pressing ”Connect to Aibo” button in the main dialog. A statusmessage should confirm that the connection was established.

3. Start the factory by pressing the button ”Start cutting”.

132

Page 147: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Appendix G

Source Code

Table G.1 and G.2 describe the content of the files included in the system. Source code for theapplication on the PC controller for the LEGO system is contained in Table G.1, whereas sourcecode for the AIBO is contained in Table G.2.

The application for the PC controller is programmed in C++, as a Windows 32-bit applicationusing Microsoft Visual C++ 6.0 (MSVC++ 6.0) and its Microsoft Foundation Classes (MFC).The LEGO system is programmed in brickOS version 0.2.6, which is based on C and C++.

Table G.1: Files for the PC controller and the LEGO system – developed specifically for thiswork

Asset File name Content description

PC ball3.dsw MSVC++ 6.0 Workspace file

ball3.dsp MSVC++ 6.0 Ball3 Projectfile

ball3.rc Ball3 resources (Dialog)

resource.h

stdafx.* MSVC++ 6.0 standard files

ball3.cpp Implementation of Ball3 class

ball3.h

ball3dlg.cpp Implementation of Ball3Dlgclass

ball3dlg.h

talking.cpp Implementation of Talkingclass

talking.h

LEGO system factory.c Implementation of factoryclass (code for the RCX)

133

Page 148: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Source Code

The code for AIBO is based on the sample programs BallTrackingHead and ImageCapturecontained in the OPEN-R-SDK from Sony. The original files are modified in order to use thetwo applications together, as well as to add the feature of detecting a green man in addition tothe pink ball.

Table G.2: Files to be downloaded to the memory stick for AIBO – modified Sony codeFolder File name Description of updates

./ Makefile updated to build both BallTrackingHeadand PictureSaver applications

./BallTrackingHead/ BallTrackingHead.h detection of green staff added

BallTrackingHead Image.cc

./MS/OPEN-R/MW/CONF

CONNECT.CFG added interfaces between TCPGatewayand oVirtualRobotComm

OBJECT.CFG added TCPGateway object

ROBOTGW.CFG config file for mapping TCPGateway in-terfaces to TCP ports added

./PictureSaver Makefile makefiles for the PictureSaver RP-OPEN-R application

Makefile.common

PictureSaver.cc periodically saves images to a BMP filein PC file system, mutual exclusion usingfile-locking mechanism

PictureSaver.h

PictureSaver.ocf specifies the objects in the PictureSaverapplication

stub.cfg specifies the services of the PictureSaverapplication

./RP/host/MS/OPEN-R/MW/CONF

CONNECT.CFG maps the TCPGateway connection to Pic-tureSaver services

HOSTGW.CFG specifies the mapping of TCPGateway in-terfaces to TCP ports

OBJECT.CFG list of the PictureSaver object binary files

134

Page 149: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

#include <conio.h>#include <unistd.h>#include <dmotor.h>#include <dsensor.h>#include <dsound.h>#include <semaphore.h>#include <time.h>#include <string.h>#include <lnp/lnp.h>#include <lnp/lnp−logical.h>

#define MAX_MSG_LEN 20

#define START_MESSAGE "S"#define STOP_MESSAGE " P"#define USER_START_MESSAGE "U"#define USER_STOP_MESSAGE "X"#define STAFF_MESSAGE "A"#define NOSTAFF_MESSAGE "N"

#define OPEN_GATE rev#define CLOSE_GATE fwd

#define LOCK_GATE fwd#define UNLOCK_GATE rev

#define ON_BUTTON TOUCH_1#define OFF_BUTTON TOUCH_2#define GATE_SENSOR SENSOR_3#define PRESSED_THRESHOLD 0xc000#define OPEN_THRESHOLD 0x0e000

unsigned char msg[100];int arrived;

enum { wait_start, stopped, stopped_staff, stopped_staff_in, running, running_staff, disconnected } state;

void new_message( const unsigned char *data, unsigned char length){ if (data[0] == 0) return; // skip wakeup messages memcpy(msg, data, length); msg[length] = ’ \0’; arrived = 1;}

//interface between postoffice and the main applicationunsigned char *to_send; // packet accepted by postoffice for sendingunsigned char order_nr; // number of packet to be sentunsigned char sent; // packet # sent last timeunsigned char received[MAX_MSG_LEN+1]; // packet receivedsem_t po_sem; // must be locked to access these data int po_shutdown; // set to 1 to shutdown postofficelong po_timeout; // time after which confirming message from peer must arriveint connection_lost; // set to disconnected when connection is lost

#define CHECK_MSG_INTERVAL 20#define SEND_MSG_INTERVAL 150 // message sent every ... msec#define COMMUNICATION_TIMEOUT 650 // after 1 and 1/2 sec. the confirmation should arrive#define SEND_MSG_TIMEOUT 7000 // if unable to send msg using post office for 3 sec, fail#define RECEIVE_MSG_TIMEOUT 1000 // if unable to receive msg using post office for 1 sec, fail

Page 1/8factory.c#define MAX_TIMEOUT_COUNT 10 // how many msg delivery timeouts lead to // state ’disconnected’

void switch_gate_position(MotorDirection d){ motor_b_speed(MAX_SPEED / 3); motor_b_dir(d); msleep(70); while (GATE_SENSOR > PRESSED_THRESHOLD) msleep(1); motor_b_dir(brake); msleep(200); motor_b_dir(off);}

void lock_light_on(){ motor_c_speed(31); motor_c_dir(fwd);}

void lock_light_off(){ motor_c_speed(31); motor_c_dir(off);}

void lock_gate(MotorDirection d){ motor_c_speed(255); motor_c_dir(d); msleep(150); motor_c_dir(off); if (d == LOCK_GATE) lock_light_on(); else lock_light_off();}

void cputs_state(){ switch(state) { case wait_start: cputs(" READY"); break; case stopped: cputs(" STOP"); break; case stopped_staff: cputs(" HELLO"); break; case stopped_staff_in: cputs(" REPAR"); break; case running: cputs(" RUN "); break; case running_staff: cputs(" HELLO"); break; case disconnected: cputs(" C ERR"); break; }}

int postoffice( int argc, char **argv){ //postoffice’s local data unsigned char msgout[MAX_MSG_LEN+3]; // packet being sent/confirmed unsigned char *sending = msgout + 2; unsigned char sending_nr; // packet # being sent unsigned char receiving[MAX_MSG_LEN+1]; // packet being received/confirmed int id; // id of last message sent (i.e. id of last co

Page 2/8factory.c

135

Page 150: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

nfirmed msg + 1) int peer_ready = 0; // communicating peer is ready to receive message time_t time_arrived; // timestamp of the last message that arrived time_t ta2; int to_take_new_packet; // local flag int timeout_count; // how many consecutive timeouts occured char *disp = " M000";

//note: lego side of the communication is first receiving a message //initialize data structures to_send = 0; // post office ready to accept new package sent = 0; // post office ready to send new package to eter order_nr = 1; // we start with packet # 1 received[0] = ’ \0’; // no message received from eter yet sending = msgout + 2; // make sure static pointer is initialized sending[0] = ’ \0’; // no message to send id = 32; // expecting id==32 //stay away from < 32! (i.e. ESC) po_shutdown = 0; // po running sem_init(&po_sem, 0, 1); // initialize semaphore time_arrived = 0; // just for order sending_nr = 0; // likewise timeout_count = 0; // no timeouts yet connection_lost = 0; // disconnection did not occur yet

lock_gate(LOCK_GATE); //wait for the first message while (!arrived) msleep(CHECK_MSG_INTERVAL); state = stopped; cputs_state();

//main post office loop while (!po_shutdown) { //try to receive a message while ((!arrived) && (sys_time < time_arrived + po_timeout)) msleep(CHECK_MSG_INTERVAL);

//timeout or message arrived if (!arrived) { msg[0] = ’ \0’; ta2 = sys_time; timeout_count++; if (timeout_count == MAX_TIMEOUT_COUNT) { connection_lost = 1; return 0; } } else { arrived = 0; timeout_count = 0; peer_ready = msg[1] − ’ 0’; // save ready_to_receive info from peer time_arrived = sys_time; ta2 = sys_time; //show the number of received msg on the LCD disp[1] = ’ 0’ + msg[0] / 100; disp[2] = ’ 0’ + msg[0] % 100 / 10; disp[3] = ’ 0’ + msg[0] % 10;

Page 3/8factory.c //cputs(disp); }

if (msg[0] != ( unsigned char)id) // confirmation message did not arrive { //receive message if not received yet and buffer ready if (receiving[0]) { sem_wait(&po_sem); if (received[0] == ’ \0’) { strcpy(received, receiving); receiving[0] = ’ \0’; } sem_post(&po_sem); } id−−; if (id == 31) id = 127; //will send previous message below } else // confirmation message did arrive as expected { sem_wait(&po_sem); to_take_new_packet = 0; if (sending[0] == ’ \0’) { //we don’t take new packet unless the previous //send request is completed if ((peer_ready) && (sent == 0)) to_take_new_packet = 1; } else if (sent == 0) // user learned that last message was sent ok { sent = sending_nr; sending[0] = ’ \0’; if (peer_ready) to_take_new_packet = 1; } if (to_take_new_packet) { if (to_send == 0) // no new packet to be sent sending[0] = ’ \0’; else { strcpy(sending, to_send); sending_nr = order_nr; order_nr = order_nr % 255 + 1; to_send = 0; } } if (receiving[0] == ’ \0’) strcpy(receiving, msg+2);

if (received[0] == ’ \0’) { strcpy(received, receiving); receiving[0] = ’ \0’; } //our range of ids is 32..127 id = (id − 31) % 96 + 32; sem_post(&po_sem); } //wait until it’s time to send

Page 4/8factory.c

136

Page 151: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

while (sys_time < time_arrived + SEND_MSG_INTERVAL) msleep(CHECK_MSG_INTERVAL); msgout[0] = ( unsigned char)id; msgout[1] = (receiving[0] == ’ \0’) + ’ 0’; lnp_integrity_write(msgout, 2 + strlen(sending)); id = (id − 31) % 96 + 32; time_arrived = ta2; }

sem_destroy(&po_sem); return 0;} //returns 0 if message not sent, otherwise returns 1int msg_send( unsigned char *a){ time_t t = sys_time; unsigned char nr;

sem_wait(&po_sem); while ((sys_time < t + SEND_MSG_TIMEOUT) && (to_send != 0)) { sem_post(&po_sem); msleep(SEND_MSG_INTERVAL/3); sem_wait(&po_sem); } if (to_send) // still not ready, i.e. timeout reached { sem_post(&po_sem); return 0; } to_send = a; nr = order_nr;

sem_post(&po_sem); msleep(SEND_MSG_INTERVAL/3); //give the post office chance to send it sem_wait(&po_sem); while ((sys_time < t + SEND_MSG_TIMEOUT) && (sent != nr)) { sem_post(&po_sem); msleep(SEND_MSG_INTERVAL/3); sem_wait(&po_sem); } if (sent != nr) // still not sent, i.e. timeout reached { sem_post(&po_sem); return 0; } sent = 0; sem_post(&po_sem); return 1;} //returns the length of message received, or 0 if timeout or msg bigger; use msg_peek() to see if//message arrived. maxsize includes the terminating ’\0’ char.int msg_receive( unsigned char *b, int maxsize){ time_t t = sys_time;

sem_wait(&po_sem);

Page 5/8factory.c while ((sys_time < t + RECEIVE_MSG_TIMEOUT) && (received[0] == ’ \0’)) { sem_post(&po_sem); msleep(SEND_MSG_INTERVAL/3); sem_wait(&po_sem); } if (received[0] == ’ \0’) //no msg within timeout { sem_post(&po_sem); return 0; } if (strlen(received) < maxsize) strcpy(b, received); else b[0] = ’ \0’; received[0] = ’ \0’; sem_post(&po_sem); return strlen(b);} //returns 0 if no message ready, otherwise the length of the messageint msg_peek(){ int ln; sem_wait(&po_sem); ln = strlen(received); sem_post(&po_sem); return ln;}

int main( int argc, char **argv) { unsigned char m[10]; pid_t sending_thread; int b;

state = wait_start; arrived = 0; lnp_integrity_set_handler(new_message); //start the postoffice thread po_timeout = COMMUNICATION_TIMEOUT; sending_thread = execi(postoffice, 0, 0, PRIO_NORMAL, DEFAULT_STACK_SIZE);

motor_a_speed(MAX_SPEED); motor_a_dir(off); switch_gate_position(CLOSE_GATE); msleep(100); lock_gate(LOCK_GATE); cputs_state(state);

do {

//check IR message buffer if (connection_lost) //if connection has been lost, stop everything { motor_a_dir(off); switch_gate_position(CLOSE_GATE); lock_gate(LOCK_GATE); state = disconnected; cputs_state(); dsound_system(DSOUND_BEEP); msleep(100); dsound_system(DSOUND_BEEP); msleep(100);

Page 6/8factory.c

137

Page 152: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

dsound_system(DSOUND_BEEP); msleep(100); do { msleep(100); } while(1); }

if (msg_peek()) { //message arrived, get it msg_receive(m, 10); } else m[0] = ’\0’; //indicates no message

b = 0; switch (state) { case stopped: if (strcmp(m, STAFF_MESSAGE) == 0) { state = stopped_staff; lock_gate(UNLOCK_GATE); cputs_state(); } else if (strcmp(m, START_MESSAGE) == 0) { state = running; motor_a_speed(MAX_SPEED); motor_a_dir(fwd); cputs_state(); } break; case stopped_staff: if (GATE_SENSOR > OPEN_THRESHOLD) { state = stopped_staff_in; switch_gate_position(OPEN_GATE); cputs_state(); } else if (strcmp(m, NOSTAFF_MESSAGE) == 0) { state = stopped; lock_gate(LOCK_GATE); cputs_state(); } else if ((strcmp(m, START_MESSAGE) == 0) || (b = ON_BUTTON)) { if (b && (!msg_send(USER_START_MESSAGE))) { //could not deliver user start message to PC controller dsound_system(DSOUND_BEEP); break; } state = running_staff; motor_a_dir(fwd); cputs_state(); } break; case stopped_staff_in: if (ON_BUTTON) { switch_gate_position(CLOSE_GATE); state = stopped_staff; cputs_state(); while (ON_BUTTON) msleep(20); } break;

Page 7/8factory.c case running: if ((strcmp(m, STOP_MESSAGE) == 0) || (b = OFF_BUTTON)) { motor_a_dir(off); state = stopped; cputs_state(); if (b) msg_send(USER_STOP_MESSAGE); } else if (strcmp(m, STAFF_MESSAGE) == 0) { lock_gate(UNLOCK_GATE); state = running_staff; cputs_state(); } break; case running_staff: if (GATE_SENSOR > OPEN_THRESHOLD) { state = stopped_staff_in; motor_a_dir(off); switch_gate_position(OPEN_GATE); cputs_state(); msg_send(USER_STOP_MESSAGE); } else if (strcmp(m, NOSTAFF_MESSAGE) == 0) { lock_gate(LOCK_GATE); state = running; cputs_state(); } else if ((strcmp(m, STOP_MESSAGE) == 0) || (b = OFF_BUTTON)) { motor_a_dir(off); state = stopped_staff; cputs_state(); if (b) msg_send(USER_STOP_MESSAGE); } break; } msleep(20); } while (1);

return 0;}

Page 8/8factory.c

138

Page 153: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

## Copyright 2002 Sony Corporation ## Permission to use, copy, modify, and redistribute this software for# non−commercial use is hereby granted.## This software is provided "as is" without warranty of any kind,# either expressed or implied, including but not limited to the# implied warranties of fitness for a particular purpose.#

COMPONENTS=BallTrackingHead MovingHead2 MovingLegs2 LostFoundSound ../PowerMonitor/PowerMonitorRPCOMPONENTS=PictureSaverINSTALLDIR=$(shell pwd)/MSRPINSTALLDIR=$(shell pwd)/RP/host/MSTARGETS=all install clean

.PHONY: $(TARGETS)

$(TARGETS):for dir in $(COMPONENTS); do \

(cd $$dir && $(MAKE) INSTALLDIR=$(INSTALLDIR) $@) \donefor dir in $(RPCOMPONENTS); do \

(cd $$dir && $(MAKE) INSTALLDIR=$(RPINSTALLDIR) $@) \done

Page 1/1Makefile//// Copyright 2002 Sony Corporation //// Permission to use, copy, modify, and redistribute this software for// non−commercial use is hereby granted.//// This software is provided "as is" without warranty of any kind,// either expressed or implied, including but not limited to the// implied warranties of fitness for a particular purpose.//

#ifndef BallTrackingHead_h_DEFINED#define BallTrackingHead_h_DEFINED

#include <list>using namespace std;

#include <OPENR/OObject.h>#include <OPENR/OSubject.h>#include <OPENR/OObserver.h>#include <OPENR/ODataFormats.h>#include <OPENR/OFbkImage.h>#include <BallTrackingHeadData.h>#include "def.h"

enum BallTrackingHeadState { BTHS_IDLE, BTHS_START, BTHS_HEAD_ZERO_POS, BTHS_LEGS_SLEEPING, BTHS_SEARCHING_BALL, BTHS_TRACKING_BALL};

static const char * const FBK_LOCATOR = "PRM:/r1/c1/c2/c3/i1−FbkImageSensor:F1";static const char * const JOINT_LOCATOR[] = { "PRM:/r1/c1−Joint2:j1", // HEAD TILT "PRM:/r1/c1/c2−Joint2:j2" // HEAD PAN};

class BallTrackingHead : public OObject {public: BallTrackingHead(); virtual ~BallTrackingHead() {}

OSubject* subject[numOfSubject]; OObserver* observer[numOfObserver];

virtual OStatus DoInit (const OSystemEvent& event); virtual OStatus DoStart (const OSystemEvent& event); virtual OStatus DoStop (const OSystemEvent& event); virtual OStatus DoDestroy(const OSystemEvent& event); void NotifyImage(const ONotifyEvent& event); void NotifySensor(const ONotifyEvent& event); void NotifyMovingHeadResult(const ONotifyEvent& event); void NotifyMovingLegsResult(const ONotifyEvent& event); void NotifyLostFoundSoundResult(const ONotifyEvent& event);

private: static const size_t NUM_COMMAND_VECTOR = 4; static const size_t NUM_SENSOR_VECTOR = 2; static const size_t NUM_JOINTS = 2; static const size_t NUM_FRAMES = 5;

Page 1/2BallTrackingHead.h

139

Page 154: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

static const int TILT_INDEX = 0; static const int PAN_INDEX = 1; static const byte BALL_THRESHOLD = 8; static const int FOUND_THRESHOLD = 2; static const int LOST_THRESHOLD = 7; static const OCdtChannel BALL_CDT_CHAN = ocdtCHANNEL0; static const OCdtChannel STAFF_CDT_CHAN = ocdtCHANNEL1; static const double FIELD_VIEW_H = 57.6; static const double FIELD_VIEW_V = 47.8;

static const int WHAT_BALL = 1; static const int WHAT_STAFF = 2; void OpenPrimitives(); void NewCommandVectorData(); void PlaySound(BallTrackingHeadCommandType type);

void SetCdtVectorDataOfPinkBall(); void SetCdtVectorDataOfGreenStaff(); bool CentroidAndDeltaAngle( const OFbkImage& cdtImage, int * xcentroid, int * ycentroid, double * delta_pan, double * delta_pan);

void InitSensorIndex(OSensorFrameVectorData* sensorVec); void GetPanTiltAngle(longword frameNum, double * pan, double * tilt);

void SearchBall(); void TrackBall(longword frameNum, double delta_pan, double delta_pan); void MoveHead( double s_pan, double s_tilt, double e_pan, double e_tilt, double *r_pan, double *r_tilt, double pan_limit, double tilt_limit); void SetJointValue(RCRegion* rgn, int idx, double start, double end); RCRegion* FindFreeRegion();

BallTrackingHeadState ballTrackingHeadState; OPrimitiveID fbkID; OPrimitiveID jointID[NUM_JOINTS]; RCRegion* region[NUM_COMMAND_VECTOR]; bool initSensorIndex; int sensoridx[NUM_JOINTS]; list<RCRegion*> sensorRegions; double lastRefPan; double lastRefTilt; int what;};

#endif // BallTrackingHead_h_DEFINED

Page 2/2BallTrackingHead.h//// Copyright 2002 Sony Corporation //// Permission to use, copy, modify, and redistribute this software for// non−commercial use is hereby granted.//// This software is provided "as is" without warranty of any kind,// either expressed or implied, including but not limited to the// implied warranties of fitness for a particular purpose.//

#include <OPENR/OPENRAPI.h>#include <OPENR/OSyslog.h>#include " BallTrackingHead.h"

voidBallTrackingHead::NotifyImage( const ONotifyEvent& event){ static int found = 0; static int lost = 0;

int xc, yc; // centroid double d_pan, d_tilt; // delta angle

if (ballTrackingHeadState == BTHS_IDLE) return; // do nothing

OFbkImageVectorData* imageVec = (OFbkImageVectorData*)event.Data(0);

OFbkImageInfo* info = imageVec−>GetInfo(ofbkimageLAYER_C); byte* data = imageVec−>GetData(ofbkimageLAYER_C); OFbkImage cdtImage(info, data, ofbkimageBAND_CDT);

if (ballTrackingHeadState == BTHS_SEARCHING_BALL) {

if (cdtImage.ColorFrequency(BALL_CDT_CHAN) >= BALL_THRESHOLD) { found++; what = WHAT_BALL; } else if (cdtImage.ColorFrequency(STAFF_CDT_CHAN) >= BALL_THRESHOLD) { what = WHAT_STAFF; found++; } else { found = 0; SearchBall(); } if (found == FOUND_THRESHOLD) { if (what == WHAT_BALL) OSYSPRINT((" ### BALL FOUND ### \n")); else OSYSPRINT((" ### STAFF FOUND ###\n")); PlaySound(BTHCMD_PLAY_FOUND_SOUND); found = 0; CentroidAndDeltaAngle(cdtImage, &xc, &yc, &d_pan, &d_tilt); TrackBall(info−>frameNumber, d_pan, d_tilt); }

} else if (ballTrackingHeadState == BTHS_TRACKING_BALL) {

if ((cdtImage.ColorFrequency(BALL_CDT_CHAN) >= BALL_THRESHOLD) || (cdtImage.ColorFrequency(STAFF_CDT_CHAN) >= BALL_THRESHOLD)) { lost = 0;

Page 1/4BallTrackingHead_Image.cc

140

Page 155: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

CentroidAndDeltaAngle(cdtImage, &xc, &yc, &d_pan, &d_tilt); TrackBall(info−>frameNumber, d_pan, d_tilt); } else { lost++; }

if (lost == LOST_THRESHOLD) { if (what == WHAT_BALL) OSYSPRINT((" ### BALL LOST ### \n")); else OSYSPRINT((" ### STAFF LOST ###\n")); PlaySound(BTHCMD_PLAY_LOST_SOUND); SearchBall(); lost = 0; } } observer[event.ObsIndex()]−>AssertReady();}

void Setcdt(OCdtInfo* cdt, int Y_segment, float Cr_max, float Cr_min, float Cb_max, float Cb_min){ cdt−>Set(Y_segment, ( unsigned char )((Cr_max + 0.5) * 255), ( unsigned char )((Cr_min + 0.5) * 255), ( unsigned char )((Cb_max + 0.5) * 255), ( unsigned char )((Cb_min + 0.5) * 255));}

voidBallTrackingHead::SetCdtVectorDataOfPinkBall(){ OSYSDEBUG((" BallTrackingHead::SetCdtVectorDataOfPinkBall()\n"));

OStatus result; MemoryRegionID cdtVecID; OCdtVectorData* cdtVec; OCdtInfo* cdt;

result = OPENR::NewCdtVectorData(&cdtVecID, &cdtVec); if (result != oSUCCESS) { OSYSLOG1((osyslogERROR, " %s : %s %d", " ImageObserver::SetCdtVectorDataOfPinkBall()", " OPENR::NewCdtVectorData() FAILED", result)); return; }

cdtVec−>SetNumData(1);

cdt = cdtVec−>GetInfo(0); cdt−>Init(fbkID, BALL_CDT_CHAN);

// // cdt−>Set(Y_segment, Cr_max, Cr_min, Cb_max, Cb_min) // cdt−>Set( 0, 230, 150, 190, 120); cdt−>Set( 1, 230, 150, 190, 120); cdt−>Set( 2, 230, 150, 190, 120); cdt−>Set( 3, 230, 150, 190, 120); cdt−>Set( 4, 230, 150, 190, 120); cdt−>Set( 5, 230, 150, 190, 120); cdt−>Set( 6, 230, 150, 190, 120); cdt−>Set( 7, 230, 150, 190, 120); cdt−>Set( 8, 230, 150, 190, 120); cdt−>Set( 9, 230, 150, 190, 120); cdt−>Set(10, 230, 150, 190, 120); cdt−>Set(11, 230, 150, 190, 120);

Page 2/4BallTrackingHead_Image.cc cdt−>Set(12, 230, 150, 190, 120); cdt−>Set(13, 230, 150, 190, 120); cdt−>Set(14, 230, 150, 190, 120); cdt−>Set(15, 230, 150, 190, 120); cdt−>Set(16, 230, 150, 190, 120); cdt−>Set(17, 230, 150, 190, 120); cdt−>Set(18, 230, 150, 190, 120); cdt−>Set(19, 230, 150, 190, 120); cdt−>Set(20, 230, 160, 190, 120); cdt−>Set(21, 230, 160, 190, 120); cdt−>Set(22, 230, 160, 190, 120); cdt−>Set(23, 230, 160, 190, 120); cdt−>Set(24, 230, 160, 190, 120); cdt−>Set(25, 230, 160, 190, 120); cdt−>Set(26, 230, 160, 190, 120); cdt−>Set(27, 230, 160, 190, 120); cdt−>Set(28, 230, 160, 190, 120); cdt−>Set(29, 230, 160, 190, 120); cdt−>Set(30, 230, 160, 190, 120); cdt−>Set(31, 230, 160, 190, 120);

result = OPENR::SetCdtVectorData(cdtVecID); if (result != oSUCCESS) { OSYSLOG1((osyslogERROR, " %s : %s %d", " ImageObserver::SetCdtVectorDataOfPinkBall()", " OPENR::SetCdtVectorData() FAILED", result)); }

result = OPENR::DeleteCdtVectorData(cdtVecID); if (result != oSUCCESS) { OSYSLOG1((osyslogERROR, " %s : %s %d", " ImageObserver::SetCdtVectorDataOfPinkBall()", " OPENR::DeleteCdtVectorData() FAILED", result)); }}

voidBallTrackingHead::SetCdtVectorDataOfGreenStaff(){ OSYSDEBUG((" BallTrackingHead::SetCdtVectorDataOfGreenStaff()\n"));

OStatus result; MemoryRegionID cdtVecID; OCdtVectorData* cdtVec; OCdtInfo* cdt;

result = OPENR::NewCdtVectorData(&cdtVecID, &cdtVec); if (result != oSUCCESS) { OSYSLOG1((osyslogERROR, " %s : %s %d", " ImageObserver::SetCdtVectorDataOfGreenStaff()", " OPENR::NewCdtVectorData() FAILED", result)); return; }

cdtVec−>SetNumData(1);

cdt = cdtVec−>GetInfo(0); cdt−>Init(fbkID, STAFF_CDT_CHAN);

// // Setcdt(cdt,Y_segment, Cr_max, Cr_min, Cb_max, Cb_min) //

Page 3/4BallTrackingHead_Image.cc

141

Page 156: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

for ( int lum = 0; lum < 32; lum++) Setcdt(cdt, lum, −0.03, −0.5, −0.015, −0.5);

result = OPENR::SetCdtVectorData(cdtVecID); if (result != oSUCCESS) { OSYSLOG1((osyslogERROR, " %s : %s %d", " ImageObserver::SetCdtVectorDataOfGreenStaff()", " OPENR::SetCdtVectorData() FAILED", result)); }

result = OPENR::DeleteCdtVectorData(cdtVecID); if (result != oSUCCESS) { OSYSLOG1((osyslogERROR, " %s : %s %d", " ImageObserver::SetCdtVectorDataOfGreenStaff()", " OPENR::DeleteCdtVectorData() FAILED", result)); }}

boolBallTrackingHead::CentroidAndDeltaAngle( const OFbkImage& cdtImage, int* xcentroid, int* ycentroid, double* delta_pan, double* delta_tilt){ int w = cdtImage.Width(); int h = cdtImage.Height(); byte* ptr = cdtImage.Pointer();

int xsum = 0; int ysum = 0; int npixels = 0; // Last line is not used because of TagInfo. for ( int y = 0; y < h−1; y++) { for ( int x = 0; x < w; x++) { if (what == WHAT_BALL) { if (*ptr++ & BALL_CDT_CHAN) { xsum += x; ysum += y; npixels++; } } else if (*ptr++ & STAFF_CDT_CHAN) {

xsum += x; ysum += y; npixels++; }

} }

if (npixels != 0) { *xcentroid = xsum / npixels; *ycentroid = ysum / npixels; *delta_pan = −1.0 * FIELD_VIEW_H * (*xcentroid − w/2.0) / w; *delta_tilt = −1.0 * FIELD_VIEW_V * (*ycentroid − h/2.0) / h; return true; } else { *xcentroid = 0; *ycentroid = 0; *delta_pan = 0.0; *delta_tilt = 0.0; return false; }}

Page 4/4BallTrackingHead_Image.cc## ballTrackingHead <−> movingHead2#BallTrackingHead.MovingHead.BallTrackingHeadCommand.S MovingHead.Command.BallTrackingHeadCommand.OMovingHead.Result.BallTrackingHeadResult.S BallTrackingHead.MovingHead.BallTrackingHeadResult.O

## ballTrackingHead <−> movingLegs2#BallTrackingHead.MovingLegs.BallTrackingHeadCommand.S MovingLegs.Command.BallTrackingHeadCommand.OMovingLegs.Result.BallTrackingHeadResult.S BallTrackingHead.MovingLegs.BallTrackingHeadResult.O

## ballTrackingHead <−> lostFoundSound#BallTrackingHead.LostFoundSound.BallTrackingHeadCommand.S LostFoundSound.Command.BallTrackingHeadCommand.OLostFoundSound.Result.BallTrackingHeadResult.S BallTrackingHead.LostFoundSound.BallTrackingHeadResult.O

## ballTrackingHead <−> ovirtualRobotComm#OVirtualRobotComm.FbkImageSensor.OFbkImageVectorData.S BallTrackingHead.Image.OFbkImageVectorData.OOVirtualRobotComm.Sensor.OSensorFrameVectorData.S BallTrackingHead.Sensor.OSensorFrameVectorData.OBallTrackingHead.Joint.OCommandVectorData.S OVirtualRobotComm.Effector.OCommandVectorData.O

## movingHead2, movingLegs2 −> ovirtualRobotComm#MovingHead.Move.OCommandVectorData.S OVirtualRobotComm.Effector.OCommandVectorData.OMovingLegs.Move.OCommandVectorData.S OVirtualRobotComm.Effector.OCommandVectorData.O

## lostFoundSound −> ovirtualRobotAudioComm#LostFoundSound.Play.OSoundVectorData.S OVirtualRobotAudioComm.Speaker.OSoundVectorData.O

# TCP Gateway <−> ovirtualRobotComm

TCPGateway.Effector.OCommandVectorData.S OVirtualRobotComm.Effector.OCommandVectorData.OOVirtualRobotComm.Sensor.OSensorFrameVectorData.S TCPGateway.Sensor.OSensorFrameVectorData.OOVirtualRobotComm.FbkImageSensor.OFbkImageVectorData.S TCPGateway.FbkImageSensor.OFbkImageVectorData.O

Page 1/1CONNECT.CFG

142

Page 157: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

FOUND_SOUND /MS/OPEN−R/MW/DATA/P/FOUND.WAVLOST_SOUND /MS/OPEN−R/MW/DATA/P/LOST.WAV

Page 1/1DESIGNDB.CFG/MS/OPEN−R/MW/OBJS/POWERMON.BIN/MS/OPEN−R/MW/OBJS/BALLTRCK.BIN/MS/OPEN−R/MW/OBJS/MVHEAD2.BIN/MS/OPEN−R/MW/OBJS/MVLEGS2.BIN/MS/OPEN−R/MW/OBJS/LFSOUND.BIN/MS/OPEN−R/SYSTEM/OBJS/TCPGW.BIN

Page 1/1OBJECT.CFG

143

Page 158: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

## ROBOTGW.CFG −− Robot TCPGateway Configuration#

## OPEN−R API port#TCPGateway.Proxy.AperiosMessage.P 59001

## TCPGateway Service#TCPGateway.Sensor.OSensorFrameVectorData.O 59002TCPGateway.Effector.OCommandVectorData.S 59003TCPGateway.FbkImageSensor.OFbkImageVectorData.O 59004#TCPGateway.Mic.OSoundVectorData.O 59005#TCPGateway.Speaker.OSoundVectorData.S 59006

Page 1/1ROBOTGW.CFG## Copyright 2002 Sony Corporation ## Permission to use, copy, modify, and redistribute this software for# non−commercial use is hereby granted.## This software is provided "as is" without warranty of any kind,# either expressed or implied, including but not limited to the# implied warranties of fitness for a particular purpose.#

OPENRSDK_ROOT?=/usr/local/OPEN_R_SDKCP=cpINSTALLDIR=../RP/host/MSSTRIP=stripMKBIN=g++STUBGEN=$(OPENRSDK_ROOT)/RP_OPEN_R/bin/rp−openr−stubgen2MKBINFLAGS=OPENRCONFIG=$(OPENRSDK_ROOT)/RP_OPEN_R/bin/rp−openr−configLIBS=‘$(OPENRCONFIG) −−libs‘CXXFLAGS= \

−O2 \−g \−I. \−I.. \‘$(OPENRCONFIG) −−cflags‘

OCF=

VPATH=.

.PHONY: all install clean

all: pictureSaver.bin

%.o: %.cc$(CXX) $(CXXFLAGS) −o $@ −c $^

PictureSaverStub.cc: stub.cfg$(STUBGEN) $^

pictureSaver.bin: PictureSaverStub.o PictureSaver.o BMP.o $(OCF)$(MKBIN) $(MKBINFLAGS) −o $@ $^ $(LIBS)$(STRIP) $@

install: pictureSaver.bin$(CP) $^ $(INSTALLDIR)/OPEN−R/MW/OBJS/PICSAVER.BIN

clean:rm −f *.o *.bin *.elf *.snap.ccrm −f PictureSaverStub.cc def.h entry.hrm −f $(INSTALLDIR)/OPEN−R/MW/OBJS/PICSAVER.BIN

Page 1/1Makefile

144

Page 159: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

##

# NOTE: This makefile is included by the makefiles in the# subdirectories.

.PHONY: all install clean

all: pictureSaver.bin

%.o: %.cc$(CXX) $(CXXFLAGS) −o $@ −c $^

PictureSaverStub.cc: stub.cfg$(STUBGEN) $^

pictureSaver.bin: PictureSaverStub.o PictureSaver.o $(OCF)$(MKBIN) $(MKBINFLAGS) −o $@ $^ $(LIBS)$(STRIP) $@

install: pictureSaver.bin$(CP) $^ $(INSTALLDIR)/OPEN−R/MW/OBJS/PICSAVER.BIN

clean:rm −f *.o *.bin *.elf *.snap.ccrm −f PictureSaverStub.cc def.h entry.hrm −f $(INSTALLDIR)/OPEN−R/MW/OBJS/PICSAVER.BIN

Page 1/1Makefile.common//// Copyright 2002 Sony Corporation //// Permission to use, copy, modify, and redistribute this software for// non−commercial use is hereby granted.//// This software is provided "as is" without warranty of any kind,// either expressed or implied, including but not limited to the// implied warranties of fitness for a particular purpose.//

#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <OPENR/OSyslog.h>#include <OPENR/core_macro.h>#include " PictureSaver.h"#include " BMP.h"

PictureSaver::PictureSaver(){}

OStatusPictureSaver::DoInit( const OSystemEvent& event){ NEW_ALL_SUBJECT_AND_OBSERVER; REGISTER_ALL_ENTRY; SET_ALL_READY_AND_NOTIFY_ENTRY; return oSUCCESS;}

OStatusPictureSaver::DoStart( const OSystemEvent& event){ imageState = IOS_START;

ENABLE_ALL_SUBJECT; ASSERT_READY_TO_ALL_OBSERVER; return oSUCCESS;}

OStatusPictureSaver::DoStop( const OSystemEvent& event){ imageState = IOS_IDLE;

DISABLE_ALL_SUBJECT; DEASSERT_READY_TO_ALL_OBSERVER; return oSUCCESS;}

OStatusPictureSaver::DoDestroy( const OSystemEvent& event){ DELETE_ALL_SUBJECT_AND_OBSERVER; return oSUCCESS;}

int PictureSaver::FileExists( char *name){ struct stat st; if (stat(name, &st) == 0) return 1; return 0;

Page 1/2PictureSaver.cc

145

Page 160: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

}

void PictureSaver::FileCreate( char *name){ FILE *f; f = fopen(name, " w+"); fprintf(f, " lock\n"); fclose(f);

return;}

voidPictureSaver::Notify( const ONotifyEvent& event){ OFbkImageVectorData* fbkImageVectorData = (OFbkImageVectorData*)event.Data(0);

if (imageState == IOS_IDLE) { return; // do nothing }

SaveData(fbkImageVectorData); for ( int i = 0; i < WAITING_REPETITIONS; i++) { if (FileExists(WANT_READ)) { FileCreate(CAN_READ); do { usleep(WAITING_DELAY); } while (FileExists(CAN_READ) || FileExists(WANT_READ)); break; } usleep(WAITING_DELAY); } ready: observer[event.ObsIndex()]−>AssertReady(event.SenderID());}

voidPictureSaver::SaveData(OFbkImageVectorData* imageVec){ char name[128]; BMP bmp; sprintf(name, IMAGE_FILE); OSYSPRINT((" writing %s ...\n", name)); bmp.SaveYCrCb2RGB(name, imageVec, ofbkimageLAYER_H);

OSYSPRINT((" done.\n"));}

Page 2/2PictureSaver.cc//// Copyright 2002 Sony Corporation //// Permission to use, copy, modify, and redistribute this software for// non−commercial use is hereby granted.//// This software is provided "as is" without warranty of any kind,// either expressed or implied, including but not limited to the// implied warranties of fitness for a particular purpose.//

#ifndef PictureSaver_h_DEFINED#define PictureSaver_h_DEFINED

#include <OPENR/OObject.h>#include <OPENR/OSubject.h>#include <OPENR/OObserver.h>#include " def.h"

#define CAN_READ " /samplePrograms/CAN_READ.LOCK"#define WANT_READ "/samplePrograms/WANT_READ.LOCK"#define IMAGE_FILE " /samplePrograms/intruder.bmp"

//between each two image saves, wait WAITING_DELAY * WAITING_REPETITIONS [usec]#define WAITING_DELAY 1000#define WAITING_REPETITIONS 1

enum ImageState { IOS_IDLE, IOS_START};

class PictureSaver : public OObject {public: PictureSaver(); virtual ~PictureSaver() {}

OSubject* subject[numOfSubject]; OObserver* observer[numOfObserver];

virtual OStatus DoInit ( const OSystemEvent& event); virtual OStatus DoStart ( const OSystemEvent& event); virtual OStatus DoStop ( const OSystemEvent& event); virtual OStatus DoDestroy( const OSystemEvent& event);

void Notify( const ONotifyEvent& event);

private:

ImageState imageState; void SaveData(OFbkImageVectorData* imageVec); void FileCreate( char *name); int FileExists( char *name);

};

#endif // PictureSaver_h_DEFINED

Page 1/1PictureSaver.h

146

Page 161: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

object pictureSaver 3072 16384 128 cache notlb kernel

Page 1/1PictureSaver.ocf////

ObjectName : PictureSaverNumOfOSubject : 1NumOfOObserver : 1Service : "PictureSaver.DummySubject.DoNotConnect.S", null, nullService : "PictureSaver.Image.OFbkImageVectorData.O", null, Notify()

Page 1/1stub.cfg

147

Page 162: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

TCPGateway.FbkImageSensor.OFbkImageVectorData.S PictureSaver.Image.OFbkImageVectorData.O

Page 1/1CONNECT.CFG!ROBOT_PROXY 59001 10.0.1.100TCPGateway.Sensor.OSensorFrameVectorData.S 59002 10.0.1.100TCPGateway.Effector.OCommandVectorData.O 59003 10.0.1.100TCPGateway.FbkImageSensor.OFbkImageVectorData.S 59004 10.0.1.100

Page 1/1HOSTGW.CFG

148

Page 163: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

/MS/OPEN−R/MW/OBJS/PICSAVER.BIN

Page 1/1OBJECT.CFG// ball3.h : main header file for the BALL3 application//

#if ! defined(AFX_BALL3_H__AAB6C188_FFCB_4C03_A0DD_5F979AB83BDF__INCLUDED_)#define AFX_BALL3_H__AAB6C188_FFCB_4C03_A0DD_5F979AB83BDF__INCLUDED_

#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000

#ifndef __AFXWIN_H__#error include ’ stdafx.h’ before including this file for PCH

#endif

#include " resource.h" // main symbols

/////////////////////////////////////////////////////////////////////////////// CBall3App:// See ball3.cpp for the implementation of this class//

class CBall3App : public CWinApp{public:

CBall3App();

// Overrides// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CBall3App)public:virtual BOOL InitInstance();//}}AFX_VIRTUAL

// Implementation

//{{AFX_MSG(CBall3App)// NOTE − the ClassWizard will add and remove member functions h

ere.// DO NOT EDIT what you see in these blocks of generated code

!//}}AFX_MSGDECLARE_MESSAGE_MAP()

};

/////////////////////////////////////////////////////////////////////////////

//{{AFX_INSERT_LOCATION}}// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_BALL3_H__AAB6C188_FFCB_4C03_A0DD_5F979AB83BDF__INCLUDED_)

Page 1/1ball3.h

149

Page 164: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

// ball3.cpp : Defines the class behaviors for the application.//

#include "stdafx.h"#include <windows.h>#include <Winbase.h>#include <process.h>

#include "ball3.h"#include "ball3Dlg.h"#include "talking.h"

#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif

DWORD WINAPI ThreadFunc( LPVOID lpParam );

/////////////////////////////////////////////////////////////////////////////// CBall3App

BEGIN_MESSAGE_MAP(CBall3App, CWinApp)//{{AFX_MSG_MAP(CBall3App)

// NOTE − the ClassWizard will add and remove mapping macros here.

// DO NOT EDIT what you see in these blocks of generated code!

//}}AFX_MSGON_COMMAND(ID_HELP, CWinApp::OnHelp)

END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////// CBall3App construction

CBall3App::CBall3App(){

// TODO: add construction code here,// Place all significant initialization in InitInstance

}

/////////////////////////////////////////////////////////////////////////////// The one and only CBall3App object

CBall3App theApp;

/////////////////////////////////////////////////////////////////////////////// CBall3App initialization

BOOL CBall3App::InitInstance(){

// Standard initialization// If you are not using these features and wish to reduce the size// of your final executable, you should remove from the following// the specific initialization routines you do not need.

#ifdef _AFXDLLEnable3dControls(); // Call this when using MFC in a

shared DLL#else

Enable3dControlsStatic(); // Call this when linking to MFC statically

Page 1/3ball3.cpp#endif

DEBUG_INIT;

CBall3Dlg dlg;

m_pMainWnd = &dlg;

//create new thread for communication with AIBO and LEGO

DWORD dwThreadId, dwThrdParam = 1; HANDLE hThread, hpoThread, hguiThread; char szMsg[80]; Talking comm(&dlg); ::comm = &comm;

hguiThread = ::CreateThread( NULL, // default security attributes 0, // use default stack size GuiThread, // thread function &dwThrdParam, // argument to thread function 0, // use default creation flags &dwThreadId); // returns the thread identifier

// Check the return value for success. if (hguiThread == NULL) { wsprintf( szMsg, "CreateThread for GUI thread failed." ); MessageBox( NULL, szMsg, "main", MB_OK ); } else { CloseHandle( hguiThread ); }

hThread = ::CreateThread( NULL, // default security attributes 0, // use default stack size AiboThread, // thread function &dwThrdParam, // argument to thread function 0, // use default creation flags &dwThreadId); // returns the thread identifier

// Check the return value for success. if (hThread == NULL) { wsprintf( szMsg, "CreateThread for Aibo thread failed." ); MessageBox( NULL, szMsg, "main", MB_OK ); } else { CloseHandle( hThread ); }

hpoThread = ::CreateThread( NULL, // default security attributes 0, // use default stack size IRThread, // thread function &dwThrdParam, // argument to thread function 0, // use default creation flags &dwThreadId); // returns the thread identifier

Page 2/3ball3.cpp

150

Page 165: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

// Check the return value for success. if (hpoThread == NULL) { wsprintf( szMsg, " CreateThread for IR thread failed." ); MessageBox( NULL, szMsg, " main", MB_OK ); } else { CloseHandle( hpoThread ); }

int nResponse = dlg.DoModal();for ( int i=0; i < 100; i++)

{ Sleep(50); Yield(); }

if (nResponse == IDOK){

// possibly place code here to handle when the dialog is// dismissed with OK

}else if (nResponse == IDCANCEL){

// possibly place code here to handle when the dialog is// dismissed with Cancel

}

dlg.DestroyWindow(); comm.stopTalking();

// Since the dialog has been closed, return FALSE so that we exit the// application, rather than start the application’s message pump.return FALSE;

}

Page 3/3ball3.cpp//Microsoft Developer Studio generated resource script.//#include "resource.h"

#define APSTUDIO_READONLY_SYMBOLS///////////////////////////////////////////////////////////////////////////////// Generated from the TEXTINCLUDE 2 resource.//#include "afxres.h"

/////////////////////////////////////////////////////////////////////////////#undef APSTUDIO_READONLY_SYMBOLS

/////////////////////////////////////////////////////////////////////////////// English (U.S.) resources

#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)#ifdef _WIN32LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US#pragma code_page(1252)#endif //_WIN32

#ifdef APSTUDIO_INVOKED///////////////////////////////////////////////////////////////////////////////// TEXTINCLUDE//

1 TEXTINCLUDE DISCARDABLE BEGIN "resource.h\0"END

2 TEXTINCLUDE DISCARDABLE BEGIN "#include ""afxres.h""\r\n" "\0"END

3 TEXTINCLUDE DISCARDABLE BEGIN "#define _AFX_NO_SPLITTER_RESOURCES\r\n" "#define _AFX_NO_OLE_RESOURCES\r\n" "#define _AFX_NO_TRACKER_RESOURCES\r\n" "#define _AFX_NO_PROPERTY_RESOURCES\r\n" "\r\n" "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" "#ifdef _WIN32\r\n" "LANGUAGE 9, 1\r\n" "#pragma code_page(1252)\r\n" "#endif //_WIN32\r\n" "#include ""res\\ball3.rc2"" // non−Microsoft Visual C++ edited resources\r\n" "#include ""afxres.rc"" // Standard components\r\n" "#endif\r\n" "\0"END

#endif // APSTUDIO_INVOKED

///////////////////////////////////////////////////////////////////////////////

Page 1/4ball3.rc

151

Page 166: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

// Icon//

// Icon with lowest ID value placed first to ensure application icon// remains consistent on all systems.IDR_MAINFRAME ICON DISCARDABLE "res\\ball3.ico"

///////////////////////////////////////////////////////////////////////////////// Dialog//

IDD_ABOUTBOX DIALOG DISCARDABLE 0, 0, 235, 55STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENUCAPTION "About ball3"FONT 8, "MS Sans Serif"BEGIN ICON IDR_MAINFRAME,IDC_STATIC,7,7,21,20 LTEXT "ball3 Version 1.0, May/June 2003",IDC_STATIC,40,10,119, 8,SS_NOPREFIX LTEXT "Survelliance of the factory robot system using mobile 4−legged robot", IDC_STATIC,40,25,128,23 DEFPUSHBUTTON "OK",IDOK,178,7,50,14,WS_GROUPEND

IDD_BALL3_DIALOG DIALOGEX 0, 0, 347, 279STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENUEXSTYLE WS_EX_APPWINDOWCAPTION "Survelliance of the factory field"FONT 8, "MS Sans Serif"BEGIN DEFPUSHBUTTON "E&xit",IDOK,280,105,60,15 LTEXT "Status information from the survelliance security−critical robot system:", IDC_STATIC,7,193,244,8 PUSHBUTTON "Stop cutting",IDC_BUTTON1,280,65,60,15 PUSHBUTTON "Start cutting",IDC_BUTTON2,280,44,60,15 LTEXT "Status information from the factory safety−critical robotic system:", IDC_STATIC,7,127,237,10 EDITTEXT IDC_EDIT1,7,137,333,49,ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_READONLY | WS_VSCROLL EDITTEXT IDC_EDIT2,7,204,333,55,ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_READONLY | WS_VSCROLL PUSHBUTTON "Connect to Aibo",IDC_BUTTON3,280,17,60,15 EDITTEXT IDC_EDIT3,7,264,118,12,ES_AUTOHSCROLL | ES_READONLY | NOT WS_BORDER EDITTEXT IDC_EDIT4,223,264,117,12,ES_AUTOHSCROLL | ES_READONLY | NOT WS_BORDER PUSHBUTTON "",BITMAP1,7,17,128,103,BS_BITMAP | BS_FLAT | NOT WS_TABSTOP PUSHBUTTON "",BITMAP2,143,17,128,103,BS_BITMAP | BS_FLAT | NOT WS_TABSTOP LTEXT "Current view:",IDC_STATIC,7,7,128,10 LTEXT "Recently detected:",IDC_STATIC,143,7,128,10END

#ifndef _MAC///////////////////////////////////////////////////////////////////////////////// Version//

Page 2/4ball3.rc

VS_VERSION_INFO VERSIONINFO FILEVERSION 1,0,0,1 PRODUCTVERSION 1,0,0,1 FILEFLAGSMASK 0x3fL#ifdef _DEBUG FILEFLAGS 0x1L#else FILEFLAGS 0x0L#endif FILEOS 0x4L FILETYPE 0x1L FILESUBTYPE 0x0LBEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904B0" BEGIN VALUE "CompanyName", "\0" VALUE "FileDescription", "ball3 MFC Application\0" VALUE "FileVersion", "1, 0, 0, 1\0" VALUE "InternalName", "ball3\0" VALUE "LegalCopyright", "Copyright (C) 2003\0" VALUE "LegalTrademarks", "\0" VALUE "OriginalFilename", "ball3.EXE\0" VALUE "ProductName", "ball3 Application\0" VALUE "ProductVersion", "1, 0, 0, 1\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 ENDEND

#endif // !_MAC

///////////////////////////////////////////////////////////////////////////////// DESIGNINFO//

#ifdef APSTUDIO_INVOKEDGUIDELINES DESIGNINFO DISCARDABLE BEGIN IDD_ABOUTBOX, DIALOG BEGIN LEFTMARGIN, 7 RIGHTMARGIN, 228 TOPMARGIN, 7 BOTTOMMARGIN, 48 END

IDD_BALL3_DIALOG, DIALOG BEGIN LEFTMARGIN, 7 RIGHTMARGIN, 340 TOPMARGIN, 7 BOTTOMMARGIN, 276 ENDEND#endif // APSTUDIO_INVOKED

Page 3/4ball3.rc

152

Page 167: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

///////////////////////////////////////////////////////////////////////////////// String Table//

STRINGTABLE DISCARDABLE BEGIN IDS_ABOUTBOX "&About ball3..."END

#endif // English (U.S.) resources/////////////////////////////////////////////////////////////////////////////

#ifndef APSTUDIO_INVOKED///////////////////////////////////////////////////////////////////////////////// Generated from the TEXTINCLUDE 3 resource.//#define _AFX_NO_SPLITTER_RESOURCES#define _AFX_NO_OLE_RESOURCES#define _AFX_NO_TRACKER_RESOURCES#define _AFX_NO_PROPERTY_RESOURCES

#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)#ifdef _WIN32LANGUAGE 9, 1#pragma code_page(1252)#endif //_WIN32#include "res\ball3.rc2" // non−Microsoft Visual C++ edited resources#include "afxres.rc" // Standard components#endif

/////////////////////////////////////////////////////////////////////////////#endif // not APSTUDIO_INVOKED

Page 4/4ball3.rc// ball3Dlg.h : header file//

#include <windows.h>#include <afxwin.h>

#if ! defined(AFX_BALL3DLG_H__1228B302_87E7_47F2_A1D2_E1705C0D9724__INCLUDED_)#define AFX_BALL3DLG_H__1228B302_87E7_47F2_A1D2_E1705C0D9724__INCLUDED_

#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000

#include " talking.h"

#define AIBOTEXT_LENGTH 10000#define LEGOTEXT_LENGTH 10000

#define INTRUDER_IMAGE " C:\\Cygwin\\cygwin−packages−1.3.17\\release\\samplePrograms\\intruder.bmp"#define CAN_READ " C:\\Cygwin\\cygwin−packages−1.3.17\\release\\samplePrograms\\CAN_READ.LOCK"#define WANT_READ "C:\\Cygwin\\cygwin−packages−1.3.17\\release\\samplePrograms\\WANT_READ.LOCK"

/////////////////////////////////////////////////////////////////////////////// CBall3Dlg dialog

class CBall3Dlg : public CDialog{// Constructionpublic:

CBall3Dlg(CWnd* pParent = NULL); // standard constructor void printAibo( char *str); void printLego( char *str); void LoadPicture( int which_one); //which one == 1 or 2

PROCESS_INFORMATION telnet_pinfo; friend DWORD WINAPI GuiThread( LPVOID lpParam ); int gui_starting, gui_shutdown;

// Dialog Data//{{AFX_DATA(CBall3Dlg)enum { IDD = IDD_BALL3_DIALOG };CButton m_bitmap2;CButton m_bitmap1;CEdit m_factorystatus;CEdit m_aibostatus;CEdit m_aibobox;CEdit m_legobox;//}}AFX_DATA

// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CBall3Dlg)protected:virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV suppo

rt//}}AFX_VIRTUAL

// Implementationprotected:

HICON m_hIcon;

// Generated message map functions

Page 1/2ball3Dlg.h

153

Page 168: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

//{{AFX_MSG(CBall3Dlg)virtual BOOL OnInitDialog();afx_msg void OnSysCommand(UINT nID, LPARAM lParam);afx_msg void OnPaint();afx_msg HCURSOR OnQueryDragIcon();afx_msg void OnButton3();afx_msg void OnButton2();afx_msg void OnButton1();virtual void OnOK();//}}AFX_MSGDECLARE_MESSAGE_MAP()

private: void updateFactoryStatus(); void updateAiboStatus();

char aibotext[AIBOTEXT_LENGTH]; char legotext[LEGOTEXT_LENGTH]; char *factory_status_str; char *aibo_status_str; int will_show_2;};

//{{AFX_INSERT_LOCATION}}// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_BALL3DLG_H__1228B302_87E7_47F2_A1D2_E1705C0D9724__INCLUDED_)

Page 2/2ball3Dlg.h// ball3Dlg.cpp : implementation file//

#include "stdafx.h"#include "ball3.h"#include "ball3Dlg.h"#include "talking.h"

#include <sys/types.h>#include <sys/stat.h>

#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif

//global reference to dlg for thread functionsstatic CBall3Dlg *dlg;//1/0 flag indicating change of status textsstatic int update = 0;

/////////////////////////////////////////////////////////////////////////////// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog{public:

CAboutDlg();

// Dialog Data//{{AFX_DATA(CAboutDlg)enum { IDD = IDD_ABOUTBOX };//}}AFX_DATA

// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CAboutDlg)protected:virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support//}}AFX_VIRTUAL

// Implementationprotected:

//{{AFX_MSG(CAboutDlg)//}}AFX_MSGDECLARE_MESSAGE_MAP()

};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD){

//{{AFX_DATA_INIT(CAboutDlg)//}}AFX_DATA_INIT

}

void CAboutDlg::DoDataExchange(CDataExchange* pDX){

CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CAboutDlg)//}}AFX_DATA_MAP

}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)//{{AFX_MSG_MAP(CAboutDlg)

// No message handlers

Page 1/8ball3Dlg.cpp

154

Page 169: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

//}}AFX_MSG_MAPEND_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////// CBall3Dlg dialog

CBall3Dlg::CBall3Dlg(CWnd* pParent /*=NULL*/): CDialog(CBall3Dlg::IDD, pParent)

{//{{AFX_DATA_INIT(CBall3Dlg)//}}AFX_DATA_INIT// Note that LoadIcon does not require a subsequent DestroyIcon in Win32m_hIcon = AfxGetApp()−>LoadIcon(IDR_MAINFRAME);

//save reference to global dlg dlg = this; //initialize variables for gui updating thread gui_starting = gui_shutdown = 0; strcpy(aibotext, " <top>\r\n"); strcpy(legotext, " <top>\r\n"); update = 1; telnet_pinfo.dwProcessId = 0; // set to zero to indicate that the structure is not used}

void CBall3Dlg::DoDataExchange(CDataExchange* pDX){

CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CBall3Dlg)DDX_Control(pDX, BITMAP2, m_bitmap2);DDX_Control(pDX, BITMAP1, m_bitmap1);DDX_Control(pDX, IDC_EDIT4, m_factorystatus);DDX_Control(pDX, IDC_EDIT3, m_aibostatus);DDX_Control(pDX, IDC_EDIT2, m_aibobox);DDX_Control(pDX, IDC_EDIT1, m_legobox);//}}AFX_DATA_MAP

}

BEGIN_MESSAGE_MAP(CBall3Dlg, CDialog)//{{AFX_MSG_MAP(CBall3Dlg)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()ON_BN_CLICKED(IDC_BUTTON3, OnButton3)ON_BN_CLICKED(IDC_BUTTON2, OnButton2)ON_BN_CLICKED(IDC_BUTTON1, OnButton1)//}}AFX_MSG_MAP

END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////// CBall3Dlg message handlers

BOOL CBall3Dlg::OnInitDialog(){

CDialog::OnInitDialog();

// Add "About..." menu item to system menu.

// IDM_ABOUTBOX must be in the system command range.ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);ASSERT(IDM_ABOUTBOX < 0xF000);

CMenu* pSysMenu = GetSystemMenu(FALSE);if (pSysMenu != NULL)

Page 2/8ball3Dlg.cpp{

CString strAboutMenu;strAboutMenu.LoadString(IDS_ABOUTBOX);if (!strAboutMenu.IsEmpty()){

pSysMenu−>AppendMenu(MF_SEPARATOR);pSysMenu−>AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMe

nu);}

}

// Set the icon for this dialog. The framework does this automatically// when the application’s main window is not a dialogSetIcon(m_hIcon, TRUE); // Set big iconSetIcon(m_hIcon, FALSE); // Set small icon

// TODO: Add extra initialization here

return TRUE; // return TRUE unless you set the focus to a control}

void CBall3Dlg::OnSysCommand(UINT nID, LPARAM lParam){

if ((nID & 0xFFF0) == IDM_ABOUTBOX){

CAboutDlg dlgAbout;dlgAbout.DoModal();

}else{

CDialog::OnSysCommand(nID, lParam);}

}

// If you add a minimize button to your dialog, you will need the code below// to draw the icon. For MFC applications using the document/view model,// this is automatically done for you by the framework.

void CBall3Dlg::OnPaint() {

if (IsIconic()){

CPaintDC dc( this); // device context for painting

SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

// Center icon in client rectangleint cxIcon = GetSystemMetrics(SM_CXICON);int cyIcon = GetSystemMetrics(SM_CYICON);CRect rect;GetClientRect(&rect);int x = (rect.Width() − cxIcon + 1) / 2;int y = (rect.Height() − cyIcon + 1) / 2;

// Draw the icondc.DrawIcon(x, y, m_hIcon);

}else{

CDialog::OnPaint();}

}

// The system calls this to obtain the cursor to display while the user drags

Page 3/8ball3Dlg.cpp

155

Page 170: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

// the minimized window.HCURSOR CBall3Dlg::OnQueryDragIcon(){

return (HCURSOR) m_hIcon;}

//adds text to the Aibo status edit boxvoid CBall3Dlg::printAibo( char *str){ if (strlen(str) + 6 > AIBOTEXT_LENGTH) return;

if (strlen(str) + strlen(aibotext) > AIBOTEXT_LENGTH) strcpy(aibotext, " <top>\r\n");

strcat(aibotext, str); update = 1;}

//adds text to the lego status edit boxvoid CBall3Dlg::printLego( char *str){ if (strlen(str) + 6 > LEGOTEXT_LENGTH) return;

if (strlen(str) + strlen(legotext) > LEGOTEXT_LENGTH) strcpy(legotext, " <top>\r\n");

strcat(legotext, str); update = 1;}

//update the status string based on the current statusvoid CBall3Dlg::updateFactoryStatus(){ static factory_state_type before = started;

if (before != comm−>factory_state) { switch (comm−>factory_state) { case started: factory_status_str = " Factory started"; break; case stopped: factory_status_str = " Factory stopped"; break; } before = comm−>factory_state; update = 1; }}

//update the status string based on the current statusvoid CBall3Dlg::updateAiboStatus(){ static aibo_state_type before = connected; if (before != comm−>aibo_state) { switch (comm−>aibo_state) { case connecting: aibo_status_str = " Connecting Aibo"; break; case connected: aibo_status_str = " Aibo connected"; break; case disconnected: aibo_status_str = " Aibo disconnected"; break;

Page 4/8ball3Dlg.cpp } before = comm−>aibo_state; update = 1; }}

//START AIBO BUTTONvoid CBall3Dlg::OnButton3() { char cmd[300]; STARTUPINFO startinfo;

if (comm−>aibo_state == connected){

printAibo(" Survelliance robot is already connected\r\n"); return;}

//if one telnet is already running we need to release its handle if (telnet_pinfo.dwProcessId) { CloseHandle(telnet_pinfo.hProcess); }

//remove file if it existed unlink(LOGFILE); //prepare command line sprintf(cmd, " telnet.exe −f %s 10.0.1.100 59000", LOGFILE);

//execute the telnet that communicates with Aibo//first prepare the STARTUPINFO structure

ZeroMemory( &startinfo, sizeof(startinfo) ); startinfo.cb = sizeof(startinfo);

if (!CreateProcess( NULL, cmd, NULL, NULL, NULL, CREATE_NO_WINDOW, NULL, NULL, &startinfo, &telnet_pinfo)) {

sprintf(cmd, " fatal: cannot exec telnet.exe: %d\r\n", GetLastError()); printAibo(cmd); } else //exec successful { CloseHandle(telnet_pinfo.hThread); // we don’t need this handle, we keep the process handle though printAibo(" Attempting to connect to Aibo...\r\n"); //start the thread checking the input from Aibo and LEGO Sleep(700); //wait for telnet to create the log file comm−>startTalking(); comm−>aibo_state = connecting; }}

//START BUTTONvoid CBall3Dlg::OnButton2() { if (comm−>aibo_state != connected)

{printLego(" Factory may not be started without survelliance robot connected.\r\n");return;

}if (comm−>factory_state == started){

printLego(" Factory already started.\r\n"); return;

Page 5/8ball3Dlg.cpp

156

Page 171: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

} //start the IR communication thread comm−>factoryStarting(); //wait until it makes reliable connection (IR tower needs to //light up) Sleep(2000);

if (!comm−>msg_send(START_MESSAGE)) { printLego(" Cannot start the engine, please check that it is ready.\r\n"); return; }

//note: state changed after status from factory arrives // comm−>factory_state = started; printLego(" Engines were requested to start.\r\n");}

//STOP BUTTONvoid CBall3Dlg::OnButton1() { if (!comm−>msg_send(STOP_MESSAGE)) { printLego(" Cannot stop the engine, please call the janitor\r\n"); return; } //note: state changes after status from factory arrives // comm−>factory_state = stopped; printLego(" Engines are requested stopped\r\n");}

//exit buttonvoid CBall3Dlg::OnOK() { //shutdown factory if needed

if (comm−>factory_state == started){

printLego(" Shutdown...sending stop signal to the engines...\r\n");if (!comm−>msg_send(STOP_MESSAGE)){

printLego(" ALERT: Cannot stop the engine, please call the janitor\r\n");}else

printLego(" OK...exit in 2 sec...");Sleep(1000);

}

//stop the postoffice thread comm−>postOfficeShutdown(); Sleep(500);

//stop the thread if running comm−>stopTalking();

comm−>aiboShutdown();Sleep(500);

gui_shutdown = 1; Sleep(200);

//and close the dialogCDialog::OnOK();

}

Page 6/8ball3Dlg.cppvoid CBall3Dlg::LoadPicture( int which_one){ HBITMAP hIntruderBitmap, oldbitmap; CButton *but; struct _stat st; int counter; FILE *f;

if (which_one == 1) but = &m_bitmap1; else if (which_one == 3) but = &m_bitmap2; else { will_show_2 = 18; return; }

f = fopen(WANT_READ, " w+"); fprintf(f, " lock\n"); fclose(f);

counter = 0; while ((!_stat(CAN_READ, &st)) && (counter < 100)) //timeout after 100*30 ms = 3 sec. { Sleep(30); counter++; } if (counter == 100) DBUG_PRINT((df, " Timeout when waiting for a bitmap\n"));

if (hIntruderBitmap = (HBITMAP)LoadImage(0, INTRUDER_IMAGE, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION)) { oldbitmap = but−>SetBitmap(hIntruderBitmap); if (oldbitmap) DeleteObject(oldbitmap); } else DBUG_PRINT((df, " Cannot load bitmap from %s\n", INTRUDER_IMAGE));

unlink(CAN_READ); unlink(WANT_READ);}

//ENTRY POINT TO THE GUI UPDATING THREADDWORD WINAPI GuiThread( LPVOID lpParam ) { //wait for start command while ((!dlg−>gui_starting) && (!dlg−>gui_shutdown)) { Sleep(50); }

DBUG_PRINT((df, " gui thread starting\n"));

//every 50ms update the status text boxes in the dialog while (!dlg−>gui_shutdown) { Sleep(50); if (update) {

dlg−>updateAiboStatus(); dlg−>updateFactoryStatus();

dlg−>m_aibobox.SetWindowText(dlg−>aibotext); dlg−>m_aibobox.LineScroll(max(dlg−>m_aibobox.GetLineCount() − 6,0)); //6:NUMBER OF LINES IN THE BOX dlg−>m_legobox.SetWindowText(dlg−>legotext); dlg−>m_legobox.LineScroll(max(dlg−>m_legobox.GetLineCount() − 5,0)); //

Page 7/8ball3Dlg.cpp

157

Page 172: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

5:NUMBER OF LINES IN THE BOX dlg−>m_aibostatus.SetWindowText(dlg−>aibo_status_str); dlg−>m_factorystatus.SetWindowText(dlg−>factory_status_str); update = 0; }

dlg−>LoadPicture(1); if (dlg−>will_show_2) { dlg−>will_show_2−−; if (!dlg−>will_show_2) dlg−>LoadPicture(3); } }

DBUG_PRINT((df, " gui thread terminates.\n")); return 0;}

Page 8/8ball3Dlg.cpp#ifndef __TALKING_H__#define __TALKING_H__

#define LOGFILE " C:\\log.txt"

#define DEBUGLOG "C:\\debuglog.txt"//use DBUG_PRINT(df, ...) #define DBUG_PRINT(arglist) { FILE *df; df = fopen(DEBUGLOG, " a+"); fprintf(df, " %4ld.%3ld: ", comm−>sys_time()/1000, comm−>sys_time()%1000); fprintf arglist ; fclose(df); }#define DEBUG_INIT unlink(DEBUGLOG)

//default settings for post office thread#define CHECK_MSG_INTERVAL 20#define SEND_MSG_INTERVAL 150 // message sent every 1/2 sec#define COMMUNICATION_TIMEOUT 650 // after 1 and 1/2 sec. the confirmation should arrive#define SEND_MSG_TIMEOUT 8100 // if unable to send msg using post office for 3 sec, fail#define RECEIVE_MSG_TIMEOUT 1000 // if unable to receive msg using post office for 1 sec, fail#define MAX_TIMEOUT_COUNT 10 // how many times a timeout can occur before connection lost

#define MAX_MSG_LEN 20

#define START_MESSAGE (unsigned char *)" S"#define STOP_MESSAGE ( unsigned char *)" P"#define USER_START_MESSAGE (unsigned char *)" U"#define USER_STOP_MESSAGE (unsigned char *)" X"#define STAFF_MESSAGE (unsigned char *)" A"#define NOSTAFF_MESSAGE (unsigned char *)" N"#define ENGINES_STARTED_MESSAGE (unsigned char *) " E"#define ENGINES_STOPPED_MESSAGE (unsigned char *) " G"#define ENGINES_NOT_STARTED_MESSAGE (unsigned char *) " T"#define GATE_OPEN_MESSAGE (unsigned char *) " O"#define GATE_CLOSE_MESSAGE (unsigned char *) " C"

//return values for aibo_check#define NO_CHANGE 0#define BALL_FOUND 1#define BALL_LOST 2#define SHUTDOWN_OF_AIBO 3#define AIBO_CONNECTED 4#define STAFF_FOUND 5#define STAFF_LOST 6

/////////////////////////////////////////////////////////////////////////////// Talking:// See talking.cpp for the implementation of this class//#include <afxwin.h>

typedef enum {started, stopped} factory_state_type;typedef enum {connecting, connected, disconnected} aibo_state_type;

class Talking{public:

Talking(CDialog *dlgref); void stopTalking(); void startTalking(); void postOfficeShutdown() { po_shutdown = 1; }; void aiboShutdown() { shutdown = 1; }

Page 1/2talking.h

158

Page 173: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

void factoryStarting(); //postoffice functions int msg_send(unsigned char *a); int msg_receive(unsigned char *b, unsigned int maxsize); int msg_peek();

//legos’s sys_time simulation long sys_time(); friend DWORD WINAPI IRThread( LPVOID lpParam ); friend DWORD WINAPI AiboThread( LPVOID lpParam );

factory_state_type factory_state;aibo_state_type aibo_state;

private:

//event handler void processMessage(unsigned char *msg); //ir functions void send_ir_message(unsigned char *msg); int receive_ir_message(unsigned char *buf, unsigned int maxsize, long timeout); //aibo functions int check_aibo(); //semaphores void sem_init(HANDLE *sem, int a, int b); void sem_wait(HANDLE *sem); void sem_post(HANDLE *sem); void sem_destroy(HANDLE *sem);

CDialog *dlg; //reference to dialog object int running; //for starting/stopping/restarting communication with AIBO unsigned char msg[MAX_MSG_LEN + 3]; // received ir message saved here

//interface between postoffice thread and the rest of the application unsigned char *to_send; // packet accepted by postoffice for sending unsigned char sent; // packet nr sent last time unsigned char order_nr; // number of packet to be sent unsigned char received[MAX_MSG_LEN+1]; // packet received HANDLE po_sem; // must be locked to access these data int po_shutdown; // set to 1 to shutdown postoffice long po_timeout; // time after which confirming message from peer must arrive int factory_starting; //set to 1 to start the postoffice thread int shutdown; //aibo thread shutdown clock_t start_clock; // time of start of program (to avoid huge sys_time)};

extern Talking *comm;

#endif

Page 2/2talking.h#include "stdafx.h"#include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h>#include <Winbase.h>#include <process.h>#include <errno.h>

#include "ball3.h"#include "talking.h"#include "ball3Dlg.h"

//global reference to Talking object for the Thread functionTalking* comm;

//constructor initializes the reference to dialog class and its internal variablesTalking::Talking(CDialog* dlgref){ dlg = dlgref;

running = 0; //aibo communication not started yet factory_starting = 0; // factory communication not started yet shutdown = 0; //the user did not press EXIT yet

po_timeout = COMMUNICATION_TIMEOUT; //timeout settings for PostOffice start_clock = clock(); //sys_time() will return time elapsed since this moment

factory_state = stopped; //initialize state of the factory aibo_state = disconnected; //initialize state of survelliance robot}

//called when user exits, will terminate the communication //with survelliance robotvoidTalking::stopTalking(){ running = 0;}

//called to start the survelliance communication thread from ready modevoidTalking::startTalking(){ running = 1;}

//user pressed the START factory buttonvoidTalking::factoryStarting(){ factory_starting = 1;}

// needs to be called when the message is expected. This call will// block execution until message is received or timeout reached// returns 0 if message did not arrive or the message is too long for the buffer// the message will be returned in the buf, which must provide enough spaceintTalking::receive_ir_message(unsigned char* buf, unsigned int maxsize,

Page 1/13talking.cpp

159

Page 174: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

long timeout){ // variables used for starting/checking status of process ULONG exitcode; STARTUPINFO startinfo; PROCESS_INFORMATION ir_pinfo; char cmd[100]; FILE* f; //file handle to file where the message is saved by the ir tool long tout = sys_time() + timeout; // determine the timeout

//assume a message will not be received: buf[0] = ’ \0’; buf[1] = ’ \0’; buf[2] = ’ \0’;

//remove previous file if any unlink(" msg_received.tmp");

//execute the command for ir communication //ir receive <port> <message file> <timeout> [wakeuptower]

//execute the ir.exe //first prepare the STARTUPINFO structure ZeroMemory(&startinfo, sizeof(startinfo)); startinfo.cb = sizeof(startinfo); //prepare the command line sprintf(cmd, " ir.exe receive COM1 msg_received.tmp %ld wakeuptower", timeout);

if (!CreateProcess( NULL, cmd, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &startinfo, &ir_pinfo)) { sprintf(cmd, " fatal: cannot exec ir.exe: %d\r\n", GetLastError()); ((CBall3Dlg *) (comm−>dlg))−>printLego(cmd); return 0; } else //exec successful { CloseHandle(ir_pinfo.hThread); // we don’t need this handle, we keep the process handle though //wait until the process exits do { //determine the process exit status if (!GetExitCodeProcess(ir_pinfo.hProcess, &exitcode)) { sprintf(cmd, " GetExitCodeProcess returned FALSE, error:%d", GetLastError()); MessageBox( NULL, cmd, " FATAL", MB_OK); return 0; }

//if the program is still running, wait a little bit and check again if (exitcode == STILL_ACTIVE) Sleep(CHECK_MSG_INTERVAL / 3); } while ((exitcode == STILL_ACTIVE) && (sys_time() < tout));

//now we can close also the process handle CloseHandle(ir_pinfo.hProcess);

//did ir create any file? (i.e. did it receive any message?) if (!(f = fopen(" msg_received.tmp", " r"))) { //if not, make a note to debug log

Page 2/13talking.cpp DBUG_PRINT((df, " rec*_ir_message could not open file, errno=%d\n", errno)); return 0; } //read the received message from file fgets(( char *) buf, maxsize, f); //and close it fclose(f); //the file is not needed more, delete it unlink(" msg_received.tmp"); DBUG_PRINT((df, " message received %d:%s\n", strlen(( char *) buf), buf)); return strlen(( char *) buf); }}

//sends an ir message to RCX immediatelly, nothing is now about whether//the recipient receives itvoidTalking::send_ir_message( unsigned char* msg){ //variables used for starting the ir tool STARTUPINFO startinfo; PROCESS_INFORMATION pinfo; FILE* f; //file handle to a file where the message will be prepared char cmd[40]; //command line

//prepare the message if (!(f = fopen(" msg_to_send.tmp", " w+"))) { MessageBox( NULL, " cannot prepare message file", " FATAL", MB_OK); return; } //prints the message (msg) to the file msg_to_send.tmp (f) fprintf(f, " %c%c%s", msg[0], msg[1], msg + 2); fclose(f);

//ir send <port> <message file> //execute the ir.exe //first prepare the STARTUPINFO structure ZeroMemory(&startinfo, sizeof(startinfo)); startinfo.cb = sizeof(startinfo); //prepare the command line sprintf(cmd, " ir.exe send COM1 msg_to_send.tmp");

if (!CreateProcess( NULL, cmd, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &startinfo, &pinfo)) { sprintf(cmd, " fatal: cannot exec ir.exe: %d\r\n", GetLastError()); ((CBall3Dlg *) (comm−>dlg))−>printLego(cmd); return; } else //exec successful { CloseHandle(pinfo.hThread); // we don’t need these handles CloseHandle(pinfo.hProcess); }}

//checks for ball found or lost and returns one of the constants//BALL_FOUND, BALL_LOST, NO_CHANGE, or SHUTDOWN_OF_AIBO. First call//after Aibo was started will return AIBO_CONNECTEDintTalking::check_aibo(){

Page 3/13talking.cpp

160

Page 175: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

FILE* f; //file handle to the telnet console output log

static int found_count = 0; //how many times the ball was found before this call static int lost_count = 0; //how many times the ball was lost before static int connected_count = 0; //how many times aibo was connected (usually 0 or 1) static int found_staff_count = 0; // how many times aibo found staff before this call static int lost_staff_count = 0; // how many times aibo lost staff before this call int found = 0, lost = 0, staff_found = 0, staff_lost = 0, closed = 0, connected = 0; //new values learned from the log char ln[2048]; //each line of the log will be read here

//look at the console output f = fopen(LOGFILE, " r"); if (!f) { //the console log cannot be opened is a fatal condition MessageBox( NULL, " cannot open log file", " FATAL", MB_OK); return SHUTDOWN_OF_AIBO; }

//read all lines in the log while (fgets(ln, 1024, f)) { if (strstr(ln, " BALL FOUND")) found++; else if (strstr(ln, " systemCore")) connected = 1; else if (strstr(ln, " BALL LOST")) lost++; else if (strstr(ln, " STAFF FOUND")) staff_found++; else if (strstr(ln, " STAFF LOST")) staff_lost++; else if (strstr(ln, " AIBO SAYS BYE")) closed++; }

//file has been read, close it fclose(f);

//termination string detected if (closed) return SHUTDOWN_OF_AIBO;

//connection detection string was found if (connected > connected_count) { connected_count = connected; return AIBO_CONNECTED; } //new BALL FOUND string(s) found if (found > found_count) { found_count = found; return BALL_FOUND; } //new BALL LOST string(s) found else if (lost > lost_count) { lost_count = lost;

Page 4/13talking.cpp return BALL_LOST; } else if (staff_found > found_staff_count) { found_staff_count = staff_found; return STAFF_FOUND; } else if (staff_lost > lost_staff_count) { lost_staff_count = staff_lost; return STAFF_LOST; } //otherwise nothing new found return NO_CHANGE;}

//process a message received from the factoryvoidTalking::processMessage( unsigned char* msg){ strncpy(( char *) this−>msg, ( char *) msg, MAX_MSG_LEN); DBUG_PRINT((df, " processMessage(%s)\n", msg));

//user has started factory using ON button if (strcmp(( char *) msg, ( char *) USER_START_MESSAGE) == 0) { factory_state = started; ((CBall3Dlg *) dlg)−>printLego(" Factory reports: engines started manually.\r\n"); } //user has stopped factory using OFF button else if (strcmp(( char *) msg, ( char *) USER_STOP_MESSAGE) == 0) { factory_state = stopped; ((CBall3Dlg *) dlg)−>printLego(" Factory reports: engines stopped manually.\r\n"); } else if (strcmp(( char *) msg, ( char *) ENGINES_STARTED_MESSAGE) == 0) { ((CBall3Dlg *) dlg)−>printLego(" Factory reports: engines running.\r\n"); factory_state = started; } else if (strcmp(( char *) msg, ( char *) ENGINES_STOPPED_MESSAGE) == 0) { ((CBall3Dlg *) dlg)−>printLego(" Factory reports: engines stopped.\r\n"); factory_state = stopped; } else if (strcmp(( char *) msg, ( char *) GATE_OPEN_MESSAGE) == 0) { ((CBall3Dlg *) dlg)−>printLego(" Gate is open.\r\n"); } else if (strcmp(( char *) msg, ( char *) GATE_CLOSE_MESSAGE) == 0) { ((CBall3Dlg *) dlg)−>printLego(" Gate is closed.\r\n"); } else if (strcmp(( char *) msg, ( char *) ENGINES_NOT_STARTED_MESSAGE) == 0) { ((CBall3Dlg *) dlg)−>printLego(" Engines were not started. (gate open?)\r\n"); } //possibly react to other status messages from LEGO...

}

//ENTRY POINT TO THE AIBO COMMUNICATION THREADDWORD WINAPIAiboThread(LPVOID lpParam)

Page 5/13talking.cpp

161

Page 176: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

{ char ln[1025]; int started = 0, aibo; DWORD exitcode;

//this external loop allows to reconnect to aibo after connection was lost do { DBUG_PRINT((df, " Aibothread ready to be started.\n"));

//wait for startup command; do { Sleep(20); } while (!comm−>running);

DBUG_PRINT((df, " Aibothread started.\n"));

do { //check if telnet is still running if (!GetExitCodeProcess(((CBall3Dlg *) (comm−>dlg))−>telnet_pinfo.hProcess, &exitcode)) { //could not check − this is a fatal condition DBUG_PRINT((df, " Aibothread cannot obtain info about telnet :−(.\n")); sprintf(ln, " GetExitCodeProcess returned FALSE, error:%d", GetLastError()); MessageBox( NULL, ln, " FATAL ", MB_OK); if (comm−>factory_state == started) if (!comm−>msg_send(STOP_MESSAGE)) ((CBall3Dlg *) (comm−>dlg))−>printAibo(" ALERT! Factory shutdown unsuccessful, call janitor immediatelly!\r\n"); comm−>factory_state = stopped; comm−>stopTalking(); comm−>aibo_state = disconnected; break; }

//if telnet not running if (exitcode != STILL_ACTIVE) { DBUG_PRINT((df, " telnet terminated :−O.\n")); if (comm−>factory_state == started) { ((CBall3Dlg *) (comm−>dlg))−>printAibo(" Connection to survelliance robot lost, shutting down the factory\r\n"); if (!comm−>msg_send(STOP_MESSAGE)) ((CBall3Dlg *) (comm−>dlg))−>printAibo(" ALERT! Factory shutdown unsuccessful, call janitor immediatelly!\r\n"); else comm−>factory_state = stopped; } else ((CBall3Dlg *) (comm−>dlg))−>printAibo(" Connection to survelliance robot lost, press ’Connect’ again when ready.\r\n");

comm−>aibo_state = disconnected; comm−>stopTalking(); break; }

Page 6/13talking.cpp

//check if aibo have sent a message aibo = comm−>check_aibo(); if (aibo == SHUTDOWN_OF_AIBO) //aibo sent shutdown, or error occured { DBUG_PRINT((df, " Aibo shutdown.\n")); if (comm−>factory_state == started) { ((CBall3Dlg *) (comm−>dlg))−>printAibo(" !!! Survelliance robot stopped, shutting down the factory\r\n"); comm−>msg_send(STOP_MESSAGE); comm−>factory_state = stopped; } else ((CBall3Dlg *) (comm−>dlg))−>printAibo(" Survelliance robot stopped. Press ’Connect’ again when ready.\r\n"); comm−>aibo_state = disconnected; comm−>stopTalking(); break; } else if (aibo == AIBO_CONNECTED) //aibo detected connected { DBUG_PRINT((df, " Aibo connected.\n")); ((CBall3Dlg *) (comm−>dlg))−>printAibo(" Connection established.\r\n"); comm−>aibo_state = connected; } else if (aibo == STAFF_FOUND) //aibo sent staff found { DBUG_PRINT((df, " Aibo found staff.\n")); if (comm−>factory_starting) comm−>msg_send(STAFF_MESSAGE); ((CBall3Dlg *) (comm−>dlg))−>printAibo(" Staff in the arena, relaxed safety mode.\r\n"); ((CBall3Dlg *) (comm−>dlg))−>LoadPicture(2); } else if (aibo == STAFF_LOST) //aibo sent staff lost { DBUG_PRINT((df, " Aibo lost staff.\n")); if (comm−>factory_starting) comm−>msg_send(NOSTAFF_MESSAGE); ((CBall3Dlg *) (comm−>dlg))−>printAibo(" Staff left the factory, increased safety mode.\r\n"); } else if (aibo == BALL_FOUND) //aibo sent ball found { DBUG_PRINT((df, " Aibo found ball.\n")); ((CBall3Dlg *) (comm−>dlg))−>printAibo(" Warning: Intruder in the arena detected.\r\n"); ((CBall3Dlg *) (comm−>dlg))−>LoadPicture(2); } else if (aibo == BALL_LOST) //aibo sent ball lost { DBUG_PRINT((df, " Aibo lost ball.\n")); ((CBall3Dlg *) (comm−>dlg))−>printAibo(" Intruder disappeared.\r\n"); } //check if LEGO has sent a message

//see if message arrived if (comm−>msg_peek()) { //message arrived, fetch and process it comm−>msg_receive(( unsigned char *) ln, 10); DBUG_PRINT((df, " AiboThread(): processing msg from lego: ’%s’.\n", ln)); comm−>processMessage(( unsigned char *) ln);

Page 7/13talking.cpp

162

Page 177: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

} } while (comm−>running); // will exit using break if aibo is shutdown

DBUG_PRINT((df, " AiboThread() standby.\n")); //stop telnet if running //if (comm−>aibo_state != disconnected)

TerminateProcess(((CBall3Dlg *)(comm−>dlg))−>telnet_pinfo.hProcess, 0);

//release unused handle CloseHandle(((CBall3Dlg *) (comm−>dlg))−>telnet_pinfo.hProcess); ((CBall3Dlg *) (comm−>dlg))−>telnet_pinfo.dwProcessId = 0; //mark that structure is not used } while (!comm−>shutdown); // get ready to be started again

DBUG_PRINT((df, " AiboThread() terminates.\n")); return 0;}

//emulating sys_time from legOSlongTalking::sys_time(){ return ( long ) ((clock() − start_clock) / ((( double ) CLOCKS_PER_SEC) / 1000.0));}

//returns 0 if message not sent, otherwise returns 1//sends message reliably over IR connectionintTalking::msg_send( unsigned char * a){ long t = sys_time(); unsigned char nr;

DBUG_PRINT((df, " msg_send(%s) enter, waiting for being able to send...\n", a));

sem_wait(&po_sem); //wait until the post office thread is able to accept new packet, or until //timeout expires while ((sys_time() < t + SEND_MSG_TIMEOUT) && (to_send != 0)) { sem_post(&po_sem); Sleep(SEND_MSG_INTERVAL / 3); sem_wait(&po_sem); }

if (to_send) // still not ready, i.e. timeout reached { sem_post(&po_sem); return 0; }

DBUG_PRINT((df, " msg_send(%s) enter, sending!\n", a)); //give the pointer to message to post office and take the order number to_send = a; nr = order_nr; sem_post(&po_sem); Sleep(SEND_MSG_INTERVAL / 3); //give the post office chance to send it sem_wait(&po_sem); //wait until the message has been sent or timeout is reached

Page 8/13talking.cpp while ((sys_time() < t + SEND_MSG_TIMEOUT) && (sent != nr)) { sem_post(&po_sem); Sleep(SEND_MSG_INTERVAL / 3); sem_wait(&po_sem); } if (sent != nr) // still not sent, i.e. timeout reached { sem_post(&po_sem); DBUG_PRINT((df, " msg_send(%s) timeout\n", a)); return 0; } //clean the confirmation queue for another packet sent = 0; sem_post(&po_sem); DBUG_PRINT((df, " msg_send(%s) ok\n", a)); return 1;}

//semaphore interface (emulating POSIX semaphores on Win32)voidTalking::sem_init(HANDLE* sem, int a, int b){ *sem = CreateSemaphore( NULL, a, 10, NULL); if (!*sem) MessageBox( NULL, " Cannot create semaphore. You must exit.", " FATAL", MB_OK);}

voidTalking::sem_wait(HANDLE* sem){ WaitForSingleObject(*sem, INFINITE);}

voidTalking::sem_post(HANDLE* sem){ ReleaseSemaphore(*sem, 1, NULL);}

voidTalking::sem_destroy(HANDLE* sem){ //TODO: this crashes... :( //CloseHandle(*sem);}

//returns the length of message received, or 0 if timeout or msg bigger; //use msg_peek() to see if message arrived. maxsize includes the terminating ’\0’ char.intTalking::msg_receive( unsigned char * b, unsigned int maxsize){ long t = sys_time();

DBUG_PRINT((df, " msg_receive(%ld,%u) enter\n", b, maxsize)); sem_wait(&po_sem); while ((sys_time() < t + RECEIVE_MSG_TIMEOUT) && (received[0] == ’ \0’)) { sem_post(&po_sem); Sleep(SEND_MSG_INTERVAL / 3); sem_wait(&po_sem); }

Page 9/13talking.cpp

163

Page 178: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

if (received[0] == ’ \0’) //no msg within timeout { sem_post(&po_sem); DBUG_PRINT((df, " msg_receive(%ld,%u) timeout\n", b, maxsize)); return 0; } if (strlen(( char *) received) < maxsize) strcpy(( char *) b, ( char *) received); else b[0] = ’ \0’; received[0] = ’ \0’; sem_post(&po_sem); DBUG_PRINT((df, " msg_receive(%ld,%u) ok: %s\n", b, maxsize, b)); return strlen(( char *) b);}

//returns 0 if no message ready, otherwise the length of the messageintTalking::msg_peek(){ int ln; sem_wait(&po_sem); ln = strlen(( char *) received); sem_post(&po_sem); //DBUG_PRINT((df, "msg_peek() returns %d\n", ln)); return ln;}

//ENTRY POINT TO THE LEGO POST OFFICE COMMUNICATION THREADDWORD WINAPIIRThread(LPVOID lpParam){ //postoffice’s local data unsigned char msgout[MAX_MSG_LEN + 3]; // packet being sent/confirmed unsigned char * sending = msgout + 2; unsigned char sending_nr; // packet # being sent unsigned char receiving[MAX_MSG_LEN + 1]; // packet being received/confirmed int id; // id of last message sent (i.e. id of last confirmed msg + 1) int peer_ready; // communicating peer is ready to receive message int time_arrived; // timestamp of the last message that arrived int to_take_new_packet; // local flag int timeout_count; // how many times in a row a timeout occured

int arrived; // indicates message arrived (compatibility with lego postoffice)

//note: pc side of the communication is first sending a message

//initialize data structures comm−>to_send = 0; // post office ready to accept new package comm−>sent = 0; // post office ready to send new package to eter comm−>order_nr = 1; // first packet # is 1 comm−>received[0] = ’ \0’; // no message received from eter yet, so buffer is empty receiving[0] = ’ \0’; // no message arrived

sending = msgout + 2; // make sure static pointer is initialized sending[0] = ’ \0’; // no message to send id = 32; // first message id==32 comm−>po_shutdown = 0; // po running comm−>sem_init(&comm−>po_sem, 1, 0); // initialize semaphore time_arrived = 0; // just for order

Page 10/13talking.cpp sending_nr = 0; // likewise long xcnt = 0; // counter for startup status timeout_count = 0; // no timeouts yet

//wait for start command while ((!comm−>factory_starting) && (!comm−>po_shutdown)) { Sleep(50); if (xcnt++ == 40) ((CBall3Dlg *) (comm−>dlg))−>gui_starting = 1; }

DBUG_PRINT((df, " factory starting\n"));

//send the first (empty) message msgout[0] = ( unsigned char) id; msgout[1] = ’ 1’; comm−>send_ir_message(msgout); time_arrived = comm−>sys_time(); DBUG_PRINT((df, " init msg (%d) sent, waiting for message, time: %ld, timeout:%ld\n", id, time_arrived, time_arrived + comm−>po_timeout)); id++;

//main post office loop while (!comm−>po_shutdown) { //try to receive a message arrived = comm−>receive_ir_message(comm−>msg, 10, comm−>po_timeout);

//timeout or message arrived if (!arrived) { DBUG_PRINT((df, " message did not arrive, timeout: %ld\n", time_arrived)); timeout_count++; if (timeout_count == MAX_TIMEOUT_COUNT) ((CBall3Dlg *) (comm−>dlg))−>printLego(" Communication link broken. Call janitor immediatelly to stop the factory!\r\n"); } else { //remember the time when message arrived time_arrived = comm−>sys_time(); arrived = 0; timeout_count = 0; //retrieve the receive status of the other communicating peer peer_ready = comm−>msg[1] − ’ 0’;

DBUG_PRINT((df, " message arrived: %d,%d,’%s’.\n", comm−>msg[0], comm−>msg[1], comm−>msg + 2)); }

if (comm−>msg[0] != ( unsigned char) id) // confirmation message did not arrive { DBUG_PRINT((df, " message confirmation error − will resend same message\n")); //receive message if not received yet and user ready if (receiving[0]) { comm−>sem_wait(&comm−>po_sem); if (comm−>received[0] == ’ \0’)

Page 11/13talking.cpp

164

Page 179: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

{ strcpy(( char *) comm−>received, ( char *) receiving); receiving[0] = ’ \0’; } comm−>sem_post(&comm−>po_sem); } id−−; if (id == 31) id = 127; //will send previous message below } else // confirmation message did arrive as expected { DBUG_PRINT((df, " message confirmation ok\n")); comm−>sem_wait(&comm−>po_sem); //*** SENDING PART to_take_new_packet = 0; if (sending[0] == ’ \0’) { //we don’t start sending new packet until the previous //send request has learned that message was sent ok //and other peer must be ready to receive next packet if ((peer_ready) && (comm−>sent == 0)) to_take_new_packet = 1; } else if (comm−>sent == 0) // user learned that previous message was sent ok { //mark that the this message was sent ok comm−>sent = sending_nr; //empty sending buffer sending[0] = ’ \0’; if (peer_ready) // new packet will be sent only if peer is ready to_take_new_packet = 1; } if (to_take_new_packet) { if (comm−>to_send == 0) // no new packet to be sent sending[0] = ’ \0’; else { //copy the packet to be sent strcpy(( char *) sending, ( char *) comm−>to_send); //and remember its order nr sending_nr = comm−>order_nr; //increment the order nr comm−>order_nr = (comm−>order_nr % 255) + 1; //make it possible for new packet to be prepared for sending comm−>to_send = 0; } } //*** RECEIVING PART //if we are ready to receive a message, receive it if (receiving[0] == ’ \0’) strcpy(( char *) receiving, ( char *) comm−>msg + 2);

//if receive buffer is empty, push message further out through the system if (comm−>received[0] == ’ \0’) { strcpy(( char *) comm−>received, ( char *) receiving); //and empty the receiving buffer receiving[0] = ’ \0’; }

Page 12/13talking.cpp

//increment id (we loop only through valid 7−bit chars) id = (id − 31) % 96 + 32;

comm−>sem_post(&comm−>po_sem); }

//wait until it’s time to send while (comm−>sys_time() < time_arrived + SEND_MSG_INTERVAL) Sleep(CHECK_MSG_INTERVAL);

DBUG_PRINT((df, " sending message %d,%d,’%s’.\n", id, (receiving[0] == ’ \0’), msgout + 2));

msgout[0] = ( unsigned char ) id; msgout[1] = (receiving[0] == ’ \0’) + ’ 0’; comm−>send_ir_message(msgout); //increment id for the expected message id = (id − 31) % 96 + 32; }

comm−>sem_destroy(&comm−>po_sem); DBUG_PRINT((df, " IRThread() terminates.\n")); return 0;}

Page 13/13talking.cpp

165

Page 180: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

//{{NO_DEPENDENCIES}}// Microsoft Developer Studio generated include file.// Used by ball3.rc//#define IDM_ABOUTBOX 0x0010#define IDD_ABOUTBOX 100#define IDS_ABOUTBOX 101#define IDD_BALL3_DIALOG 102#define IDR_MAINFRAME 128#define IDC_BUTTON1 1000#define IDC_BUTTON2 1001#define IDC_EDIT1 1002#define IDC_EDIT2 1003#define IDC_BUTTON3 1004#define IDC_EDIT3 1005#define IDC_EDIT4 1006#define BITMAP1 1009#define BITMAP2 1010

// Next default values for new objects// #ifdef APSTUDIO_INVOKED#ifndef APSTUDIO_READONLY_SYMBOLS#define _APS_NEXT_RESOURCE_VALUE 130#define _APS_NEXT_COMMAND_VALUE 32771#define _APS_NEXT_CONTROL_VALUE 1011#define _APS_NEXT_SYMED_VALUE 101#endif#endif

Page 1/1resource.h// stdafx.cpp : source file that includes just the standard includes// ball3.pch will be the pre−compiled header// stdafx.obj will contain the pre−compiled type information

#include "stdafx.h"

Page 1/1StdAfx.cpp

166

Page 181: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

// stdafx.h : include file for standard system include files,// or project specific include files that are used frequently, but// are changed infrequently//

#if !defined(AFX_STDAFX_H__E501FDFB_6874_4F62_A41B_CB90DFC87966__INCLUDED_)#define AFX_STDAFX_H__E501FDFB_6874_4F62_A41B_CB90DFC87966__INCLUDED_

#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000

#define VC_EXTRALEAN // Exclude rarely−used stuff from Windows headers

#include <afxwin.h> // MFC core and standard components#include <afxext.h> // MFC extensions#include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls#ifndef _AFX_NO_AFXCMN_SUPPORT#include <afxcmn.h> // MFC support for Windows Common Controls#endif // _AFX_NO_AFXCMN_SUPPORT

//{{AFX_INSERT_LOCATION}}// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_STDAFX_H__E501FDFB_6874_4F62_A41B_CB90DFC87966__INCLUDED_)

Page 1/1StdAfx.h

167

Page 182: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

Bibliography

[1] ABS Consulting - Modeling Security Risk. Available from: http://www.jbfa.com/ [Accessed22.04.03].

[2] D. Scott Alexander, William A. Arbaugh, Angelos D. Keromytis, and Jonathan M. Smith.Safety and Security of Programmable Network Infrastructures. IEEE CommunicationsMagazine, 36:84–92, October 1998.

[3] M. Ash. LegOS HOWTO: LegOS Network Protocol. Available from:http://legos.sourceforge.net/HOWTO/x405.html [Accessed 28.06.03].

[4] Australian/New Zealand Standard AS/NZS 4360:1999 Risk Management. Strathfield:Standards Australia.

[5] B. Bagnall. Core LEGO MINDSTORMS Programming. Prentice Hall PTR, 2002.

[6] B. Barber and J. Davey. The use of the ccta risk analysis and management methodologyCRAMM. In Proc. MEDINFO92, North Holland, pages 1589–1593, 1992.

[7] D. Baum. Definitive Guide to LEGO MINDSTORMS. Apress, 2000.

[8] D. Baum, M. Gasperi, R. Hempel, and L. Villa. Extreme MINDSTORMSTM : An Advanced

Guide to LEGOr MINDSTORMSTM . Apress, 2000.

[9] B. Bing. Wireless Local Area Networks: The New Wireless Revolution. John Wiley & Sons,2002.

[10] G. Booch, J. Rumbaugh, and Jacobson I. The Unified Modeling Language User Guide.Addison-Wesley, 1999. 6th Printing April 2000.

[11] F. den Braber, R. Fredriksen, B. A. Gran, S. H. Houmb, K. Stølen, J. Ø . Aagedal, T. Dim-itrakos, and Y. C. Stamatiou. Model-based risk assessment in a component-based softwareengineering process: the CORAS approach to identify security risks, 2003. Chapter inbook titled Business Component-Based Software Engineering. Franck Barbier (ed), pages189-207, Kluwer, 2003.

[12] brickOSTM home page. Available from: http://brickos.sourceforge.net/ [Accessed 14.07.03].

[13] S. Brown. Overview of IEC 61508. design of electrical/electronic/programmable electronicsafety-related systems. Computing & Control Engineering Journal, 11:6–12, February 2000.

[14] A. Burns, J. McDermid, and J. Dobson. On the Meaning of Safety and Security. TheComputer Journal, 35:3–15, February 1992.

168

Page 183: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

BIBLIOGRAPHY

[15] Common Criteria for Information Technology Security Evaluation, 1999. Part 1: Introduc-tion and general model, August 1999, Version 2.1, CCIMB-99-031.

[16] SEISMED Project Consortium. Data Security for Healthcare. SEISMED, IOM Press, 1996.

[17] CORAS IST-2000-25031 Web Site. Available from: http://www.nr.no/coras [Acessed14.06.03].

[18] Safeware Engineering Corporation. Designing for Safety. Available from:http://www.safeware-eng.com/software-safety/design.shtml [Accessed 08.10.2002].

[19] Sony Corporation. OPEN-R SDK: Programmer’s Guide. 20030201-E-003.

[20] Sony Corporation. AIBO Wireless LAN Card: Operating Instructions, ERA-201D1, 2000.4-652-247-21(1).

[21] Sony Corporation. Entertainment Robot AIBO: Operating Instructions, ERS-210, 2000.4-652-093-21(1).

[22] T. Dimitrakos, B. Ritchie, D. Raptis, and K. Stølen. Model based Security Risk Analysis forWeb Applications: The CORAS approach. In Electronic Workshops in Computing (eWiC):EuroWeb 2002 Conference - From e-science to e-business, December 2002.

[23] G. Ferrari, A. Gombos, S. Hilmer, J. Stuber, M. Porter, J. Waldinger, and D. Laverde.Programming LEGO Mindstorms with Java. Syngress, 2002.

[24] STSARCES Standards for Safety Related Complex Electronic Systems. Annex 8: SafetyValidation of Complex Components, 2000.

[25] V. K. Garg and J. E. Wilkes. Wireless and Personal Communications Systems. PrenticeHall PTR, 1996.

[26] E. Gustafsson and A. Jonsson. Always Best Connected. IEEE Wireless Communications,10:49–55, February 2003.

[27] L. M. Halgreen and J. H. P Eloff. A Risk Analysis Model for a Medical Environment(RAMME). Technical Report, Rand Africans University, 1997.

[28] K. K. Hansen, S. O. Rogdar, and K. Sørby. Risk assessment of Safety Critical Systems: Anapproach using LEGO Mindstorms for prototyping, 2002. Project in the course SIF8094Spesialization in Software Engineering at NTNU.

[29] G. Held. Data Over Wireless Networks: Bluetooth, WAP, & Wireless LANs. McGraw Hill,2001.

[30] HiTechnic Products and Assecories. Available from: http://www.hitechnic.com/ [Accessed14.07.03].

[31] S. H. Houmb, F. den Braber, M. S. Lund, and K. Stølen. Towards a UML Profile forModel-Based Risk Assessment. In Critical systems development with UML - Proceedings ofthe UML’02 workshop, pages 79–91, September 2002.

[32] S. H. Houmb and K. Stølen. Model-based security assessment. Unpublished work. Will bepublished as a technical report at NTNU in 2003.

169

Page 184: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

BIBLIOGRAPHY

[33] IEC 61508-1: 1998 functional safety of electrical/electronic/programmable electronic safety-related systems, part 1: General requirements.

[34] IEC 61508: 2000 Functional Safety of Electrical/Electronic/Programmable Electronic(E/E/PE) Safety-Related Systems.

[35] IEEE Std 1471-2000: IEEE Recommended Practice for Architectural Description ofSoftware-Intensive Systems.

[36] U. Isaksen, J. P. Bowen, and N. Nissanke. System and Software Safety in Critical Systems.Technical Report RUCS/97/TR/062/A, 1997.

[37] ISO. About ISO: Introduction: How it all started. Available from: http://www.iso.ch/[Acessed 26.05.03].

[38] ISO/IEC 13335: Information Technology - Guidelines for the management of IT Security.http://www.iso.ch.

[39] ISO/IEC 17799: 2000 Information technology - Code of practise for information securitymanagement.

[40] E. Jonsson. An Integrated Framework for Security and Dependability. In Proceeding ofthe New Security Paradigms Workshop 1998. Charlottesville, VA, USA, September 22-25,1998.

[41] E. Jonsson, L. Stromberg, and S. Lindskog. On the functional relation between securityand dependability impairments. In Proceedings of the New Security Paradigms Workshop1999 (NSPW 1999), pages 104–111. Ontario, Canada, September 22-24, 1999.

[42] Eleanor W. Jordan, Jefry J. Machesky, and J. B. Matkowski. Systems Development: Re-quirements, Evaluation, Design, and Implementation. PWS-KENT, 1990.

[43] J. Jurjens. Principles for Secure System Design, 2002. Wolfson College, Oxford UniversityComputing Laboratory.

[44] J. Jurjens. UMLsec: Extending UML for Secure Systems Development. In UML 2002.Springer-Verlag, 2002. LNCS 2460.

[45] N. G. Leveson. Software Safety: Why, What, and How. Computing Surveys, 18(2):125–163,June 1986.

[46] N. G. Leveson. Safeware: System Safety and Computers. Addison-Wesley, 1995.

[47] B. Littlewood, S. Brocklehurst, N. Fenton, P. Mellor, S. Page, D. Wright, J. Dobson,J. McDermid, and D. Gollmann. Towards Operational Measures of Computer Security.Journal of Computer Security, 2(2-3):211–229, 1993.

[48] Mindsensors. Available from: http://www.mindsensors.com/ [Accessed 14.07.03].

[49] M. Naedele. IT-Security for Safety-Critical Automation Systems. In 5th InternationalSymposium on Programmable Electronic Systems in Safety Related Applications, Cologne,Germany, May 2002.

[50] P. Norton and M. Stockman. Peter Norton’s: Network Security Fundamentals. SAMS,1999.

170

Page 185: HOVEDOPPGAVE - Computer Science · Abstract The distinction between safety and security is not always clear. Safety and security are normally regarded as representing distinct properties

BIBLIOGRAPHY

[51] Ministry of Defence. Defence Standard 00-56 issue 2: Safety Management Requirementsfor Defence Systems, part 1: Requirements, 1996.

[52] Ministry of Defence. Defence Standard 00-58 Issue 2: Hazop Studies on Systems containingProgrammable Electronics, part 2: General Application Guidance, 2000.

[53] OPEN-R SDK. Available from: http://openr.aibo.com/ [Accessed 19.07.2003].

[54] C. P. Pfleeger. Security in Computing. Prentice-Hall International, Inc, 1997.

[55] M. Rausand. Risiko Analyse: Veiledning til NS 5814. Tapir, 1991.

[56] F. Redmill, M. Chudleigh, and J. Catmur. System Safety: HAZOP and Software HAZOP.John Wiley and Sons, 1999.

[57] J. Schiller. Mobile Communications. Addison-Wesley, 2000.

[58] W. Stallings. Network Security Essentials: Applications and Standards. Prentice Hall, Inc.,2000.

[59] V. Stavridou and B. Dutertre. From Security to Safety and Back. In Computer Security,Dependability and Assurance: From Needs to Solutions, pages 182–195, 1998.

[60] I. Stojmenovic, editor. Handbook of Wireless Networks and Mobile Computing. John Wiley& Sons, Inc, 2002.

[61] N. Storey. Safety-critical computer systems. Addison-Wesley, 1996.

[62] R.C. Summers. Secure Computing: Threats and Safeguards. McGraw-Hill, 1997.

[63] Lodderstedt T., D. Basin, and J. Doser. SecureUML: A UMLbased Modeling Language forModelDriven Security. In UML 2002, pages 426–441. Springer-Verlag, 2002. LNCS 2460.

[64] Department of Defence Trusted Computer System Evaluation Criteria, 1985. DoD 5200.28-STD, Supersedes, CSC-STD-00l-83, dtd l5 Aug 83, Library No. S225,7ll.

[65] CESG (the Communication-Electronics Security Group). the National Technical Authorityfor Information Assurance. Available from: http://www.itsec.gov.uk/ [Acessed 14.06.03].

[66] K. J. Wedde, T. Stalhane, and E. Swane. Designing safety critical systems using UML,November 17, 1999. SINTEF Telecom and Informatics.

[67] R. Winther, O-A. Johnsen, and B. A. Gran. Security Assessment of Safety Critical SystemsUsing HAZOPs, September 2001. Safecomp 2001, Budapest, Hungary, 26-28 September2001.

[68] Yasuhiko Yokote. The Apertos reflective operating system: The concept and its imple-mentation. In Andreas Paepcke, editor, Proceedings of the Conference on Object-OrientedProgramming Systems, Languages, and Applications (OOPSLA), volume 27, pages 414–434,New York, NY, 1992. ACM Press.

171