SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Downloaden Sie, um offline zu lesen
PyCon APAC 2015
ZoneIDAProc
Tzung-Bi Shih
<penvirus@gmail.com>
PyCon APAC 2015
Motivation
Course assignment of Operating System
everything is a file (descriptor)
QA engineer often checks process internal states
via checking debug logs
the log.. trustworthy?
2
PyCon APAC 2015
Related Works
Debugger (process trace-able utility)
variable monitoring / tampering
code instrumentation
3
=> debug symbols are required
=> accessing interface is domain-specific
PyCon APAC 2015
Problem Statement
4
We wish to deliver defect-less software to customers.
To verify behavior of our program is correct, QA engineer
often triggers state transition inside the process and checks
new state is as expected. However, most internal states are
available only in debug logs which may not trustworthy
enough.
We will use Instrumentation-based Dynamic Accessing Proc to
export an interface for accessing the internal states easily.
PyCon APAC 2015
Design
exporting interface
Aggregation for relevant states
structured addressing
Manipulation on specified state
fine-grained access
5
=> something like Linux proc[1]
=> directory, read-only file, read-write file
Example:
- endpoint
- ip
- port
- name
PyCon APAC 2015
Design
accessing internal state
Unawareness of aimed process
process trace
Freshness of internal states
on-demand access
dedicated (spy) thread
6
PyCon APAC 2015
Implementation
Linux proc-like interface
Virtual File System[2]
Filesystem in Userspace[3]
7
PyCon APAC 2015
Implementation
code instrumentation[4]
Easy version
gdb
Difficult version
“ptrace(2)”[5][6]
8
- LSM Yama[7]
- CAP_SYS_PTRACE
- PTRACE_TRACEME
- …
$ sudo setcap cap_sys_ptrace+eip ./gdb
PyCon APAC 2015
Example[8]
basic read/write
1 import time
2 from ida_proc import IDAProc
3
4 app = IDAProc()
5
6 @app.route('/time')
7 def ctime():
8 return time.ctime()
9
10 def register_for_data():
11 data = dict()
12 data['data'] = 'default'
13
14 @app.route('/test/data')
15 def getter():
16 return data['data']
17
18 @app.route('/test/data', method='SET')
19 def setter(d):
20 data['data'] = d
21 return data['data']
22
23 if __name__ == '__main__':
24 register_for_data()
25 app.run()
9
exported path
writable
PyCon APAC 2015
Example
spy thread
8 data = dict()
9 data['data'] = 'default'
10
11 def main():
12 while True:
13 print "[%s] data['data'] = %s" % (time.ctime(), data['data'])
14 sleep(1)
15
16 def proc():
17 app = IDAProc()
18
19 @app.route('data')
20 def getter():
21 return data['data']
22
23 @app.route('data', method='SET')
24 def setter(d):
25 data['data'] = d
26 return data['data']
27
28 def fusermount():
29 p = subprocess.Popen(['/bin/fusermount', '-u', app.get_mount_point()],
close_fds=True, shell=False)
30 p.communicate()
31 atexit.register(fusermount)
32
33 app.run()
34
35 if __name__ == '__main__':
36 t = threading.Thread(target=proc)
37 t.daemon = True
38 t.start()
39 spawn(main).join()
the spy thread has
no idea about when
will the main thread
be terminated
main thread
PyCon APAC 2015
Example
symbol explorer
9 app = IDAProc()
10
11 Endpoint = namedtuple('Endpoint', ['host', 'port'])
12 end_1 = Endpoint('1.1.1.1', 1111)
13
14 end_2 = Endpoint(host='2.2.2.2', port=2222)
15 end_3 = Endpoint(port=3333, host='3.3.3.3')
16 Pair = namedtuple('Pair', ['src', 'dst'])
17 pair = Pair(src=end_2, dst=end_3)
18
19 def make_kv(path, m, k):
20 @app.route(path)
21 def getter():
22 return m[k]
23
24 __expand_type__ = (Endpoint, Pair)
25 def expand_object(prefix, obj):
26 for k,v in obj.__dict__.items():
27 if k.startswith('__'):
28 continue
29 if (inspect.ismodule(v) or inspect.isroutine(v)
or inspect.isclass(v)):
30 continue
31
32 path = '%s/%s' % (prefix, k)
33 if type(v) in __expand_type__:
34 expand_object(path, v)
35 else:
36 make_kv(path, obj.__dict__, k)
37
38 if __name__ == '__main__':
39 expand_object('/', __main__)
40 app.run()
11
some test data
skip uninterested
PyCon APAC 2015
Example
all-in-one: target program
1 import time
2 from collections import namedtuple
3
4 Endpoint = namedtuple('Endpoint', ['host', 'port'])
5 end_1 = Endpoint('1.1.1.1', 1111)
6
7 end_2 = Endpoint(host='2.2.2.2', port=2222)
8 end_3 = Endpoint(port=3333, host='3.3.3.3')
9 Pair = namedtuple('Pair', ['src', 'dst'])
10 pair = Pair(src=end_2, dst=end_3)
11
12 data = 'default'
13
14 while True:
15 current = time.ctime()
16 print '[%s] data = %s' % (current, data)
17 time.sleep(1)
12
PyCon APAC 2015
Example
all-in-one: intruder
7 def instrument_code(pid, filename):
9 cmd = list()
10 cmd.append('./gdb')
...ignored...
15 cmd.append('--pid')
16 cmd.append('%s' % pid)
17 cmd.append(''--eval-command=call dlopen("/tmp/pycode_instrumentation.so", 2)'')
18 cmd.append(''--eval-command=call instrument_file("%s")'' % filename)
...ignored...
22
23 if __name__ == '__main__':
...ignored...
28 pid = int(sys.argv[1])
30 filename = '/tmp/zone_ida_instrumentation.py'
32 code = '''
...ignored...
72 '''
73
74 with open(filename, 'w') as f:
75 f.write(code)
76 instrument_code(pid, filename)
77
78 os.remove(filename)
13
execute code within the
target process’ memory
PyCon APAC 2015
Example
all-in-one: pycode_instrumentation
1 int instrument_file(const char *filename)
2 {
...ignored...
10 if(!_Py_IsInitialized()){
11 printf("Py_IsInitialized returned false.n");
12 goto error;
13 }
14
15 PyInterpreterState *head = _PyInterpreterState_Head();
16 if(head == NULL) {
17 printf("Interpreter is not initializedn");
18 goto error;
19 }
20
21 PyGILState_STATE pyGILState = _PyGILState_Ensure();
22 fp = fopen(filename, "r");
23 if(fp == NULL) {
24 printf("file %s doesn't exist", filename);
25 goto error;
26 }
27 _PyRun_SimpleFile(fp, "Instrumentation");
28 _PyGILState_Release(pyGILState);
29
30 if(fp)
31 fclose(fp);
32 return 1;
...ignored...
37 }
14
key point
PyCon APAC 2015
Conclusion
Proc could be an alternative configuration interface
persistent configuration file is still needed
Share states between main thread and spy thread
beware of race condition
15
PyCon APAC 2015
References
[1]: http://www.tldp.org/LDP/Linux-Filesystem-Hierarchy/html/proc.html
[2]: http://en.wikipedia.org/wiki/Virtual_file_system
[3]: http://fuse.sourceforge.net/
[4]: http://stackoverflow.com/questions/8755211/what-is-meant-by-the-term-instrumentation
[5]: http://www.linuxjournal.com/article/6100
[6]: http://www.linuxjournal.com/node/6210
[7]: https://www.kernel.org/doc/Documentation/security/Yama.txt
[8]: https://github.com/penvirus/ZoneIDAProc
16

Weitere ähnliche Inhalte

Was ist angesagt?

Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)Mr. Vengineer
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done rightPlatonov Sergey
 
Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)Mr. Vengineer
 
ISCA Final Presentaiton - Compilations
ISCA Final Presentaiton -  CompilationsISCA Final Presentaiton -  Compilations
ISCA Final Presentaiton - CompilationsHSA Foundation
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184Mahmoud Samir Fayed
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in JavaDoug Hawkins
 
Debugging of (C)Python applications
Debugging of (C)Python applicationsDebugging of (C)Python applications
Debugging of (C)Python applicationsRoman Podoliaka
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
Zn task - defcon russia 20
Zn task  - defcon russia 20Zn task  - defcon russia 20
Zn task - defcon russia 20DefconRussia
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기Ji Hun Kim
 
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)PROIDEA
 
Python sqlite3 - flask
Python   sqlite3 - flaskPython   sqlite3 - flask
Python sqlite3 - flaskEueung Mulyana
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydneyjulien.ponge
 
Rop and it's friends
Rop and it's friendsRop and it's friends
Rop and it's friendsnuc13us
 

Was ist angesagt? (20)

Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)
 
Joel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMDJoel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMD
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
 
Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)
 
Clang tidy
Clang tidyClang tidy
Clang tidy
 
Modern c++
Modern c++Modern c++
Modern c++
 
ISCA Final Presentaiton - Compilations
ISCA Final Presentaiton -  CompilationsISCA Final Presentaiton -  Compilations
ISCA Final Presentaiton - Compilations
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
 
JVM Mechanics
JVM MechanicsJVM Mechanics
JVM Mechanics
 
Debugging of (C)Python applications
Debugging of (C)Python applicationsDebugging of (C)Python applications
Debugging of (C)Python applications
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
Valgrind
ValgrindValgrind
Valgrind
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Zn task - defcon russia 20
Zn task  - defcon russia 20Zn task  - defcon russia 20
Zn task - defcon russia 20
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기
 
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
 
Python sqlite3 - flask
Python   sqlite3 - flaskPython   sqlite3 - flask
Python sqlite3 - flask
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydney
 
Rop and it's friends
Rop and it's friendsRop and it's friends
Rop and it's friends
 

Andere mochten auch

We Are Museums 2016 workshop: Introduction to usability testing
We Are Museums 2016 workshop: Introduction to usability testingWe Are Museums 2016 workshop: Introduction to usability testing
We Are Museums 2016 workshop: Introduction to usability testingTiana Tasich
 
Branding Bootcamp: Developing an Authentic Brand That Connects With Your Cust...
Branding Bootcamp: Developing an Authentic Brand That Connects With Your Cust...Branding Bootcamp: Developing an Authentic Brand That Connects With Your Cust...
Branding Bootcamp: Developing an Authentic Brand That Connects With Your Cust...Stone Soup Creative
 
Prinsip dasar dan peran koperasai
Prinsip dasar dan peran koperasaiPrinsip dasar dan peran koperasai
Prinsip dasar dan peran koperasaiNenengYuyuRohana
 
C7ce6e79 9653-42fb-9ee7-ac0cd1f8c1b5-150827185257-lva1-app6891
C7ce6e79 9653-42fb-9ee7-ac0cd1f8c1b5-150827185257-lva1-app6891C7ce6e79 9653-42fb-9ee7-ac0cd1f8c1b5-150827185257-lva1-app6891
C7ce6e79 9653-42fb-9ee7-ac0cd1f8c1b5-150827185257-lva1-app6891Vera Kovaleva
 
Presentationv1 Part1
Presentationv1 Part1Presentationv1 Part1
Presentationv1 Part1Abhishek Mago
 
TRA infographic on Australian tourism 2014
TRA infographic on Australian tourism 2014TRA infographic on Australian tourism 2014
TRA infographic on Australian tourism 2014TourismAustralia
 
Scaling Mobile Development
Scaling Mobile DevelopmentScaling Mobile Development
Scaling Mobile DevelopmentLookout
 
Verifiable, linked open knowledge that anyone can edit
Verifiable, linked open knowledge that anyone can editVerifiable, linked open knowledge that anyone can edit
Verifiable, linked open knowledge that anyone can editDario Taraborelli
 
The Public Opinion Landscape: Election 2016
The Public Opinion Landscape: Election 2016The Public Opinion Landscape: Election 2016
The Public Opinion Landscape: Election 2016GloverParkGroup
 

Andere mochten auch (15)

Neider
NeiderNeider
Neider
 
We Are Museums 2016 workshop: Introduction to usability testing
We Are Museums 2016 workshop: Introduction to usability testingWe Are Museums 2016 workshop: Introduction to usability testing
We Are Museums 2016 workshop: Introduction to usability testing
 
Branding Bootcamp: Developing an Authentic Brand That Connects With Your Cust...
Branding Bootcamp: Developing an Authentic Brand That Connects With Your Cust...Branding Bootcamp: Developing an Authentic Brand That Connects With Your Cust...
Branding Bootcamp: Developing an Authentic Brand That Connects With Your Cust...
 
Kewirausahaan
KewirausahaanKewirausahaan
Kewirausahaan
 
Prinsip dasar dan peran koperasai
Prinsip dasar dan peran koperasaiPrinsip dasar dan peran koperasai
Prinsip dasar dan peran koperasai
 
C7ce6e79 9653-42fb-9ee7-ac0cd1f8c1b5-150827185257-lva1-app6891
C7ce6e79 9653-42fb-9ee7-ac0cd1f8c1b5-150827185257-lva1-app6891C7ce6e79 9653-42fb-9ee7-ac0cd1f8c1b5-150827185257-lva1-app6891
C7ce6e79 9653-42fb-9ee7-ac0cd1f8c1b5-150827185257-lva1-app6891
 
Presentationv1 Part1
Presentationv1 Part1Presentationv1 Part1
Presentationv1 Part1
 
Dalton Sample Sheets
Dalton Sample SheetsDalton Sample Sheets
Dalton Sample Sheets
 
Keynote &amp; on stage interview (carbo)
Keynote &amp; on stage interview (carbo)Keynote &amp; on stage interview (carbo)
Keynote &amp; on stage interview (carbo)
 
TRA infographic on Australian tourism 2014
TRA infographic on Australian tourism 2014TRA infographic on Australian tourism 2014
TRA infographic on Australian tourism 2014
 
Conférence bpi identité numérique - 24 fév 2012
Conférence bpi   identité numérique - 24 fév 2012Conférence bpi   identité numérique - 24 fév 2012
Conférence bpi identité numérique - 24 fév 2012
 
Scaling Mobile Development
Scaling Mobile DevelopmentScaling Mobile Development
Scaling Mobile Development
 
13 Ways to Spook Your Audience
13 Ways to Spook Your Audience13 Ways to Spook Your Audience
13 Ways to Spook Your Audience
 
Verifiable, linked open knowledge that anyone can edit
Verifiable, linked open knowledge that anyone can editVerifiable, linked open knowledge that anyone can edit
Verifiable, linked open knowledge that anyone can edit
 
The Public Opinion Landscape: Election 2016
The Public Opinion Landscape: Election 2016The Public Opinion Landscape: Election 2016
The Public Opinion Landscape: Election 2016
 

Ähnlich wie PyCon APAC 2015 Process Internal State Access

Computer Networks Lab File
Computer Networks Lab FileComputer Networks Lab File
Computer Networks Lab FileKandarp Tiwari
 
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Data Provenance Support in...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Data Provenance Support in...Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Data Provenance Support in...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Data Provenance Support in...Data Con LA
 
'C' language notes (a.p)
'C' language notes (a.p)'C' language notes (a.p)
'C' language notes (a.p)Ashishchinu
 
Db2 For I Parallel Data Load
Db2 For I Parallel Data LoadDb2 For I Parallel Data Load
Db2 For I Parallel Data LoadThomas Wolfe
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2goMoriyoshi Koizumi
 
Runtime Code Generation and Data Management for Heterogeneous Computing in Java
Runtime Code Generation and Data Management for Heterogeneous Computing in JavaRuntime Code Generation and Data Management for Heterogeneous Computing in Java
Runtime Code Generation and Data Management for Heterogeneous Computing in JavaJuan Fumero
 
Self scaling Multi cloud nomad workloads
Self scaling Multi cloud nomad workloadsSelf scaling Multi cloud nomad workloads
Self scaling Multi cloud nomad workloadsBram Vogelaar
 
Predictive Analytics with Airflow and PySpark
Predictive Analytics with Airflow and PySparkPredictive Analytics with Airflow and PySpark
Predictive Analytics with Airflow and PySparkRussell Jurney
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+ConFoo
 
Extending Flux to Support Other Databases and Data Stores | Adam Anthony | In...
Extending Flux to Support Other Databases and Data Stores | Adam Anthony | In...Extending Flux to Support Other Databases and Data Stores | Adam Anthony | In...
Extending Flux to Support Other Databases and Data Stores | Adam Anthony | In...InfluxData
 
Sydney Oracle Meetup - execution plans
Sydney Oracle Meetup - execution plansSydney Oracle Meetup - execution plans
Sydney Oracle Meetup - execution planspaulguerin
 
RDataMining slides-r-programming
RDataMining slides-r-programmingRDataMining slides-r-programming
RDataMining slides-r-programmingYanchang Zhao
 
The ProblemUsing C programming language write a program that simul.pdf
The ProblemUsing C programming language write a program that simul.pdfThe ProblemUsing C programming language write a program that simul.pdf
The ProblemUsing C programming language write a program that simul.pdffederaleyecare
 
Assignment no39
Assignment no39Assignment no39
Assignment no39Jay Patel
 

Ähnlich wie PyCon APAC 2015 Process Internal State Access (20)

Data Analysis in Python
Data Analysis in PythonData Analysis in Python
Data Analysis in Python
 
Computer Networks Lab File
Computer Networks Lab FileComputer Networks Lab File
Computer Networks Lab File
 
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Data Provenance Support in...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Data Provenance Support in...Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Data Provenance Support in...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Data Provenance Support in...
 
'C' language notes (a.p)
'C' language notes (a.p)'C' language notes (a.p)
'C' language notes (a.p)
 
Hargun
HargunHargun
Hargun
 
Os lab final
Os lab finalOs lab final
Os lab final
 
C
CC
C
 
C++ manual Report Full
C++ manual Report FullC++ manual Report Full
C++ manual Report Full
 
Db2 For I Parallel Data Load
Db2 For I Parallel Data LoadDb2 For I Parallel Data Load
Db2 For I Parallel Data Load
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
Runtime Code Generation and Data Management for Heterogeneous Computing in Java
Runtime Code Generation and Data Management for Heterogeneous Computing in JavaRuntime Code Generation and Data Management for Heterogeneous Computing in Java
Runtime Code Generation and Data Management for Heterogeneous Computing in Java
 
Self scaling Multi cloud nomad workloads
Self scaling Multi cloud nomad workloadsSelf scaling Multi cloud nomad workloads
Self scaling Multi cloud nomad workloads
 
Predictive Analytics with Airflow and PySpark
Predictive Analytics with Airflow and PySparkPredictive Analytics with Airflow and PySpark
Predictive Analytics with Airflow and PySpark
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
 
Extending Flux to Support Other Databases and Data Stores | Adam Anthony | In...
Extending Flux to Support Other Databases and Data Stores | Adam Anthony | In...Extending Flux to Support Other Databases and Data Stores | Adam Anthony | In...
Extending Flux to Support Other Databases and Data Stores | Adam Anthony | In...
 
Sydney Oracle Meetup - execution plans
Sydney Oracle Meetup - execution plansSydney Oracle Meetup - execution plans
Sydney Oracle Meetup - execution plans
 
RDataMining slides-r-programming
RDataMining slides-r-programmingRDataMining slides-r-programming
RDataMining slides-r-programming
 
The ProblemUsing C programming language write a program that simul.pdf
The ProblemUsing C programming language write a program that simul.pdfThe ProblemUsing C programming language write a program that simul.pdf
The ProblemUsing C programming language write a program that simul.pdf
 
C Programming
C ProgrammingC Programming
C Programming
 
Assignment no39
Assignment no39Assignment no39
Assignment no39
 

Kürzlich hochgeladen

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 

Kürzlich hochgeladen (20)

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
Odoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting ServiceOdoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting Service
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 

PyCon APAC 2015 Process Internal State Access

  • 1. PyCon APAC 2015 ZoneIDAProc Tzung-Bi Shih <penvirus@gmail.com>
  • 2. PyCon APAC 2015 Motivation Course assignment of Operating System everything is a file (descriptor) QA engineer often checks process internal states via checking debug logs the log.. trustworthy? 2
  • 3. PyCon APAC 2015 Related Works Debugger (process trace-able utility) variable monitoring / tampering code instrumentation 3 => debug symbols are required => accessing interface is domain-specific
  • 4. PyCon APAC 2015 Problem Statement 4 We wish to deliver defect-less software to customers. To verify behavior of our program is correct, QA engineer often triggers state transition inside the process and checks new state is as expected. However, most internal states are available only in debug logs which may not trustworthy enough. We will use Instrumentation-based Dynamic Accessing Proc to export an interface for accessing the internal states easily.
  • 5. PyCon APAC 2015 Design exporting interface Aggregation for relevant states structured addressing Manipulation on specified state fine-grained access 5 => something like Linux proc[1] => directory, read-only file, read-write file Example: - endpoint - ip - port - name
  • 6. PyCon APAC 2015 Design accessing internal state Unawareness of aimed process process trace Freshness of internal states on-demand access dedicated (spy) thread 6
  • 7. PyCon APAC 2015 Implementation Linux proc-like interface Virtual File System[2] Filesystem in Userspace[3] 7
  • 8. PyCon APAC 2015 Implementation code instrumentation[4] Easy version gdb Difficult version “ptrace(2)”[5][6] 8 - LSM Yama[7] - CAP_SYS_PTRACE - PTRACE_TRACEME - … $ sudo setcap cap_sys_ptrace+eip ./gdb
  • 9. PyCon APAC 2015 Example[8] basic read/write 1 import time 2 from ida_proc import IDAProc 3 4 app = IDAProc() 5 6 @app.route('/time') 7 def ctime(): 8 return time.ctime() 9 10 def register_for_data(): 11 data = dict() 12 data['data'] = 'default' 13 14 @app.route('/test/data') 15 def getter(): 16 return data['data'] 17 18 @app.route('/test/data', method='SET') 19 def setter(d): 20 data['data'] = d 21 return data['data'] 22 23 if __name__ == '__main__': 24 register_for_data() 25 app.run() 9 exported path writable
  • 10. PyCon APAC 2015 Example spy thread 8 data = dict() 9 data['data'] = 'default' 10 11 def main(): 12 while True: 13 print "[%s] data['data'] = %s" % (time.ctime(), data['data']) 14 sleep(1) 15 16 def proc(): 17 app = IDAProc() 18 19 @app.route('data') 20 def getter(): 21 return data['data'] 22 23 @app.route('data', method='SET') 24 def setter(d): 25 data['data'] = d 26 return data['data'] 27 28 def fusermount(): 29 p = subprocess.Popen(['/bin/fusermount', '-u', app.get_mount_point()], close_fds=True, shell=False) 30 p.communicate() 31 atexit.register(fusermount) 32 33 app.run() 34 35 if __name__ == '__main__': 36 t = threading.Thread(target=proc) 37 t.daemon = True 38 t.start() 39 spawn(main).join() the spy thread has no idea about when will the main thread be terminated main thread
  • 11. PyCon APAC 2015 Example symbol explorer 9 app = IDAProc() 10 11 Endpoint = namedtuple('Endpoint', ['host', 'port']) 12 end_1 = Endpoint('1.1.1.1', 1111) 13 14 end_2 = Endpoint(host='2.2.2.2', port=2222) 15 end_3 = Endpoint(port=3333, host='3.3.3.3') 16 Pair = namedtuple('Pair', ['src', 'dst']) 17 pair = Pair(src=end_2, dst=end_3) 18 19 def make_kv(path, m, k): 20 @app.route(path) 21 def getter(): 22 return m[k] 23 24 __expand_type__ = (Endpoint, Pair) 25 def expand_object(prefix, obj): 26 for k,v in obj.__dict__.items(): 27 if k.startswith('__'): 28 continue 29 if (inspect.ismodule(v) or inspect.isroutine(v) or inspect.isclass(v)): 30 continue 31 32 path = '%s/%s' % (prefix, k) 33 if type(v) in __expand_type__: 34 expand_object(path, v) 35 else: 36 make_kv(path, obj.__dict__, k) 37 38 if __name__ == '__main__': 39 expand_object('/', __main__) 40 app.run() 11 some test data skip uninterested
  • 12. PyCon APAC 2015 Example all-in-one: target program 1 import time 2 from collections import namedtuple 3 4 Endpoint = namedtuple('Endpoint', ['host', 'port']) 5 end_1 = Endpoint('1.1.1.1', 1111) 6 7 end_2 = Endpoint(host='2.2.2.2', port=2222) 8 end_3 = Endpoint(port=3333, host='3.3.3.3') 9 Pair = namedtuple('Pair', ['src', 'dst']) 10 pair = Pair(src=end_2, dst=end_3) 11 12 data = 'default' 13 14 while True: 15 current = time.ctime() 16 print '[%s] data = %s' % (current, data) 17 time.sleep(1) 12
  • 13. PyCon APAC 2015 Example all-in-one: intruder 7 def instrument_code(pid, filename): 9 cmd = list() 10 cmd.append('./gdb') ...ignored... 15 cmd.append('--pid') 16 cmd.append('%s' % pid) 17 cmd.append(''--eval-command=call dlopen("/tmp/pycode_instrumentation.so", 2)'') 18 cmd.append(''--eval-command=call instrument_file("%s")'' % filename) ...ignored... 22 23 if __name__ == '__main__': ...ignored... 28 pid = int(sys.argv[1]) 30 filename = '/tmp/zone_ida_instrumentation.py' 32 code = ''' ...ignored... 72 ''' 73 74 with open(filename, 'w') as f: 75 f.write(code) 76 instrument_code(pid, filename) 77 78 os.remove(filename) 13 execute code within the target process’ memory
  • 14. PyCon APAC 2015 Example all-in-one: pycode_instrumentation 1 int instrument_file(const char *filename) 2 { ...ignored... 10 if(!_Py_IsInitialized()){ 11 printf("Py_IsInitialized returned false.n"); 12 goto error; 13 } 14 15 PyInterpreterState *head = _PyInterpreterState_Head(); 16 if(head == NULL) { 17 printf("Interpreter is not initializedn"); 18 goto error; 19 } 20 21 PyGILState_STATE pyGILState = _PyGILState_Ensure(); 22 fp = fopen(filename, "r"); 23 if(fp == NULL) { 24 printf("file %s doesn't exist", filename); 25 goto error; 26 } 27 _PyRun_SimpleFile(fp, "Instrumentation"); 28 _PyGILState_Release(pyGILState); 29 30 if(fp) 31 fclose(fp); 32 return 1; ...ignored... 37 } 14 key point
  • 15. PyCon APAC 2015 Conclusion Proc could be an alternative configuration interface persistent configuration file is still needed Share states between main thread and spy thread beware of race condition 15
  • 16. PyCon APAC 2015 References [1]: http://www.tldp.org/LDP/Linux-Filesystem-Hierarchy/html/proc.html [2]: http://en.wikipedia.org/wiki/Virtual_file_system [3]: http://fuse.sourceforge.net/ [4]: http://stackoverflow.com/questions/8755211/what-is-meant-by-the-term-instrumentation [5]: http://www.linuxjournal.com/article/6100 [6]: http://www.linuxjournal.com/node/6210 [7]: https://www.kernel.org/doc/Documentation/security/Yama.txt [8]: https://github.com/penvirus/ZoneIDAProc 16