p≡p JSON adapter
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

718 lines
26 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
2 years ago
2 years ago
2 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. # p≡p JSON Server Adapter
  2. ## Introduction
  3. The p≡p JSON Server Adapter provides a REST-like jQuery-compatible API to
  4. connect with the p≡p engine. It is language-independent and can be used by
  5. any client.
  6. ## Requirements
  7. In order to use the p≡p JSON Server Adapter, you need to build and run it.
  8. Currently, Linux (Debian 9, Ubuntu 16.04) and MacOS (10.11, 10.12) are
  9. supported, Windows is about to follow. Newer versions should also work
  10. (file a bug report if not) but are not in our main focus, yet.
  11. ## Dependencies
  12. * C++ compiler: tested with g++ 4.8, 4.9, 8.3 and clang++ 2.8. Newer versions should work, too.
  13. * GNU make
  14. * libboost-thread-dev (tested with 1.58, 1.62, 1.67, 1.70 and 1.74)
  15. * libboost-program-options-dev
  16. * libboost-filesystem-dev
  17. * [p≡p Engine](https://gitea.pep.foundation/pEp.foundation/pEpEngine/)
  18. (which needs sequoia, a patched libetpan, libboost-system-dev)
  19. * [libpEpAdapter](https://gitea.pep.foundation/pEp.foundation/libpEpAdapter/)
  20. * [webserver](https://gitea.pep.foundation/fdik/webserver)
  21. * OSSP libuuid
  22. ## Building/Installing (Linux and macOS)
  23. ### Install the dependencies
  24. Debian 9/10:
  25. ~~~~~
  26. apt install -y build-essential libboost-dev libboost-system-dev \
  27. libboost-filesystem-dev libboost-program-options-dev \
  28. libboost-thread-dev libgpgme-dev uuid-dev googletest \
  29. libevent-dev libevhtp-dev
  30. ~~~~~
  31. macOS 10.12, 10.13, 10.14:
  32. Use homebrew or macports to install the required libraries.
  33. For more explicit instructions on how to do this with macports, see the
  34. section below.
  35. Build and install the pEp Engine. Instructions can be found here:
  36. [the Engine's Readme](https://gitea.pep.foundation/pEp.foundation/pEpEngineREADME.md)
  37. ### Build and install the 'webserver' project
  38. ~~~~~
  39. cd ~/code
  40. git clone https://gitea.pep.foundation/fdik/webserver
  41. cd webserver
  42. (edit the Makefile for your $PREFIX etc.)
  43. make
  44. make install
  45. ~~~~~
  46. ### Build and install the JSON server
  47. ~~~~~
  48. cd ~/code/json-ad/server
  49. ~~~~~
  50. | :warning: FIXME: The following instructions refer to the old Makefile system that built a dynamically linked binary. This old Makefile was replaced by a hack to create a static binary. Unfortunately the config flexibility of the old Makefile system was removed in this change. |
  51. | ------ |
  52. | There is now also an ad-hoc created `Makefile.Linux`, which also can only be configured directly by editing the file. :-( |
  53. | ------ |
  54. | TODO: Re-create a more flexible build system with a `Makefile` (which is under revision control) and a `local.conf` (which is not, but contains your local-only config settings) |
  55. | ------ |
  56. Edit the build configuration to your needs in `./Makefile.conf`, or create a
  57. `./local.conf` that sets any of the make variables documented in
  58. `./Makefile.conf`.
  59. If a dependency is not found in your system's default include or library
  60. paths, you will have to specify the according paths in a make variable.
  61. Typically, this has to be done at least for the pEp Engine, libetpan and
  62. libevent.
  63. Below are two sample `./local.conf` files, for orientation.
  64. macOS 10.12, 10.13:
  65. ~~~~~
  66. PREFIX=$(HOME)/code/json-ad/build
  67. HTML_DIRECTORY=$(PREFIX)/share/pEp/json-adapter/html
  68. GTEST_DIR=$(HOME)/code/gtest/googletest
  69. BOOST_INC=-I$(HOME)/Cellar/boost/1.65.1/include
  70. BOOST_LIB=-L$(HOME)/Cellar/boost/1.65.1/lib
  71. ENGINE_INC=-I$(HOME)/code/engine/build/include
  72. ENGINE_LIB=-L$(HOME)/code/engine/build/lib
  73. ETPAN_INC=-I$(HOME)/code/libetpan/build/include
  74. ETPAN_LIB=-L$(HOME)/code/libetpan/build/lib
  75. GPGME_INC=-I$(HOME)/Cellar/gpgme/1.9.0_1/include
  76. GPGME_LIB=-L$(HOME)/Cellar/gpgme/1.9.0_1/lib
  77. UUID_INC=-I$(HOME)/Cellar/ossp-uuid/1.6.2_2/include
  78. UUID_LIB=-L$(HOME)/Cellar/ossp-uuid/1.6.2_2/lib
  79. ~~~~~
  80. Debian 9/10:
  81. ~~~~~
  82. PREFIX=$(HOME)/code/json-ad/build
  83. HTML_DIRECTORY=$(PREFIX)/share/pEp/json-adapter/html
  84. GTEST_DIR=/usr/src/googletest/googletest/
  85. ENGINE_INC=-I$(HOME)/code/engine/build/include
  86. ENGINE_LIB=-L$(HOME)/code/engine/build/lib
  87. ETPAN_INC=-I$(HOME)/code/libetpan/build/include
  88. ETPAN_LIB=-L$(HOME)/code/libetpan/build/lib
  89. ~~~~~
  90. Now, build and install the server:
  91. ~~~~~
  92. make all
  93. make install
  94. ~~~~~
  95. If you only want to build the JsonAdapter library, run `make lib` and you'll get
  96. a libjson-adapter.a
  97. With `make test` you can execute the server's tests.
  98. ### Macports
  99. [Install MacPorts](https://www.macports.org/install.php) for your version of macOS.
  100. If MacPorts is already installed on your machine, but was installed by a
  101. different user, make sure your `PATH` variable is set as follows in
  102. `~/.profile`:
  103. ```
  104. export PATH="/opt/local/bin:/opt/local/sbin:$PATH"
  105. ```
  106. Install dependencies packaged with MacPorts as follows.
  107. ```
  108. sudo port install gpgme boost ossp-uuid
  109. ```
  110. ## Building/Installing (Windows)
  111. Clone the repository from https://pep.foundation/dev/repos/pEpJSONServerAdapter and add the
  112. following projects to your MS Visual Studio solution:
  113. pEpJSONServerAdapter\build-windows\pEpJSONServerAdapter\pEpJSONServerAdapter.vcxproj
  114. pEpJSONServerAdapter\build-windows\pEpJSONServerAdapter\pEpJSONServerAdapterLibrary.vcxproj
  115. pEpJSONServerAdapter\build-windows\libevent\libevent.vcxproj
  116. In order to build, the MS VS solution also needs to build the following dependent projects:
  117. - pEpEngine (note that this requires further dependent projects)
  118. - libpEpAdapter
  119. - libevent
  120. The resulting executable is called pEpJSONServerAdapter.exe and will be placed into
  121. the `Debug` or `Release` directory of the solution.
  122. ## Running the pEp JSON Adapter
  123. You can use `make run` to start the server.
  124. 1. Run `./pEp-mini-json-adapter`. This creates a file that is readable only by the
  125. current user (`~/.pEp/json-token`) and contains the address and
  126. port the JSON adapter is listening on, normally 127.0.0.1:4223 and a
  127. "security-token" that must be given in each function call to authenticate
  128. you as the valid user.
  129. ```
  130. ./pEp-mini-json-adapter
  131. ```
  132. 2. Visit that address (normally `http://127.0.0.1:4223/`) in your
  133. JavaScript-enabled web browser to see the "JavaScript test client".
  134. 3. Call any function (`version()` or `get_gpg_path()` should work just
  135. fine) with the correct security token.
  136. ## Using the p≡p JSON Adapter
  137. In the following section, you'll find background information on how to use
  138. the adapter and its functions.
  139. ### Server startup and shutdown
  140. The JSON Server Adapter can be started on demand.
  141. It checks automatically whether an instance for the same user on the machine
  142. is already running and if yes it ends itself gracefully. (TODO!)
  143. If there is no running server found the newly started server creates the
  144. server token file and forks itself into background (if not prevented via
  145. "-d" commandline switch).
  146. ### Multi-Client handling
  147. The p≡p JSON server adapter supports multiple clients, communicating with the
  148. server at the same time. Each client instance is identified by a client ID,
  149. that the clients put into each JSON RPC request in the field "clientid".
  150. The client ID is a UUID Version 4, created by the client at startup and has to
  151. be stable while the client application runs. When the client restarts, a new
  152. client ID should be created to avoid interferene with data from the old client
  153. session.
  154. The p≡p JSON server adapter stores data (e.g., a so called "config cache", see
  155. next section) associated with each client ID. After a timeout period with no
  156. JSON RPC calls and no open client connections these data are removed
  157. automatically. Run the mini adapter with -h to see the compiled-in default
  158. timeout value.
  159. ### PEP_SESSION handling
  160. When using the p≡p engine, a `PEP_SESSION` is needed as parameter to many API
  161. functions. The p≡p JSON Server Adapter automatically creates one session per
  162. HTTP client connection (and also closes that session automatically when the
  163. client connections is closed). Therefore, the client does not need to take
  164. care of the session management. However, the client should set up a [HTTP
  165. persistent
  166. connection](https://en.wikipedia.org/wiki/HTTP_persistent_connection) to
  167. minify session creation and destruction.
  168. There is a configuration cache, that stores all `config_*()` calls and its
  169. configured values. Whenever a new PEP_SESSION is needed for this client
  170. (identified via its client ID, see previous section), all config values
  171. are applied to this new session, too, before the session is used.
  172. ### API Principles
  173. All C data types are mapped the same way, so some day the JSON wrapper can
  174. be generated from the p≡p Engine header files (or the JSON wrapper and the
  175. p≡p engine header are both generated from a common interface description
  176. file).
  177. | C type | JSON mapping |
  178. |--|--|
  179. | `bool` | JSON boolean |
  180. | `int` | JSON decimal number |
  181. | `size_t` | JSON decimal number |
  182. | `char*` (representing a UTF-8-encoded NULL-terminated string | JSON string |
  183. | `char*` (representing a binary string | base64-encoded JSON string |
  184. | `enum` | either JSON decimal number or JSON object containing one decimal number as member |
  185. | `struct` | JSON object |
  186. | linked lists (e.g. `bloblist_t`, `stringlist_t`, `identity_list` etc.) | JSON array of their member data type (without the `next` pointer) |
  187. The parameter type PEP_SESSION is handled automatically by the JSON Server
  188. Adapter and the PEP_SESSION parameter is omitted from the JSON API.
  189. #### enum types
  190. Enum types are represented as JSON objects with one member, whose name is
  191. derived from the enum type name, holding the numeric value of the enum.
  192. Some enum types are still represented directly as JSON decimal number. It
  193. shall be changed in a future version of the JSON Adapter.
  194. #### String types
  195. The JSON Server Adapter does automatic memory management for string
  196. parameters. The current p≡p Engine's API distinguish between `const char*`
  197. parameters and `char*` parameters. `const char*` normally means: the
  198. "ownership" of the string remains at the caller, so the JSON Adapter frees
  199. the string automatically after the call. `char*` normally means: the
  200. "ownership" of the string goes to the Engine, so the JSON Adapter does _not_
  201. free string.
  202. If there are functions that have a different semantics the behavior of the
  203. JSON wrapper has to be changed.
  204. #### Parameter (value) restrictions
  205. Some API functions have restrictions on their parameter values. The JSON
  206. Adapter does not know these restrictions (because it does not know the
  207. semantics of the wrapped functions at all). So it is the client's
  208. responsibility to fulfill these parameter restrictions! Especially when
  209. there are restrictions that are checked with assert() within the p≡p Engine,
  210. it is impossible for the JSON Adapter to catch failed assertions - the
  211. Engine and the Adapter process will be terminated immediatetely when the
  212. Engine is compiled in debug mode (= with enabled assert() checking).
  213. Currently there are no range checks for numerical parameter types (e.g. a
  214. JSON decimal number can hold a bigger value than the `int` parameter type of
  215. a certain C function).
  216. ### JSON RPC Requests
  217. The JSON Server Adapter offers its services via HTTP on the address and port
  218. specified on command line. It offers a simple test HTML page on the root
  219. URL.
  220. The JSON RPC functions are POST requests to the path /ja/0.1/callFunction
  221. and the JSON RPC data comes, as usual for POST requests, in the request body and
  222. must be in UTF-8 without any BOM. The `Content-Type` of the request is not relevant.
  223. Here is the body of an example request:
  224. ```
  225. {
  226. "id": 1001,
  227. "jsonrpc": "2.0",
  228. "security_token": "YSxxkNga0YUlkmdpUL6_qJuioicGK1wOC5sjGVG",
  229. "method": "import_key",
  230. "params": [
  231. "4oW5PKhgY8XdvIYQiu+KaKnZYyP5UseHD1Sfjb8HpO75m/QT/FxFI………",
  232. 4444,
  233. [
  234. "OP"
  235. ]
  236. ]
  237. }
  238. ```
  239. another example:
  240. ```
  241. {
  242. "id": 1002,
  243. "jsonrpc": "2.0",
  244. "security_token": "YSxxkNga0YUlkmdpUL6_qJuioicGK1wOC5sjGVG",
  245. "method": "myself",
  246. "params": [
  247. {
  248. "user_id": "alice",
  249. "username": "Alice in pEp land",
  250. "address": "alice@pEp.lol",
  251. "fpr": "4ABE3AAF59AC32CFE4F86500A9411D176FF00E97"
  252. }
  253. ]
  254. }
  255. ```
  256. Output parameters must be given, but their value is not relevant. The
  257. JavaScript example test client fills the output values with a dummy array,
  258. containing one string element "OP", just to ease debugging.
  259. The result contains the return value and the values of the output parameters,
  260. in reverse order:
  261. Request:
  262. ```
  263. {
  264. "id": 1003,
  265. "jsonrpc": "2.0",
  266. "security_token": "YSxxkNga0YUlkmdpUL6_qJuioicGK1wOC5sjGVG",
  267. "method": "get_languagelist",
  268. "params": [
  269. [
  270. "OP"
  271. ]
  272. ]
  273. }
  274. ```
  275. Result:
  276. ```
  277. {
  278. "outParams": [
  279. "\"en\",\"English\",\"I want to display the trustwords in English language\"……"
  280. ],
  281. "return": {
  282. "status": 0,
  283. "hex": "0 \"PEP_STATUS_OK\""
  284. }
  285. }
  286. ```
  287. ### API Reference
  288. An complete overview with all functions that are callable from the client
  289. can be found in the [API Reference](pEp JSON Server Adapter/API Reference).
  290. That API reference is a generated file (at irregular intervals) that shows the current API briefly.
  291. There is also a (currently manually written) file that holts a copy of the
  292. documentation from the Engine's header files: [API reference detail.md]
  293. BEWARE: Because this file is not auto-generated, yet, it might be even more outdated!
  294. Most of the callable functions are functions from the C API of the p≡p
  295. Engine. They are described in detail, incl. pre- and post-conditions in
  296. the appropriate C header files of the Engine, which are the authoritative source
  297. of documentation in cases of doubt.
  298. ### Authentication
  299. The JSON Server Adapter and the client have to authenticate to each other.
  300. "Authentication" in this case means "run with the same user rights". This is
  301. done by proving that each communication partner is able to read a certain
  302. file that has user-only read permissions.
  303. 0. There is a common (between client & server) algorithm to create the path
  304. and filename of the "server token file", for a given user name.
  305. The token file and its directory MUST be owned by the user and MUST be
  306. readable and writable only by the user, nobody else. Client and server
  307. check for the right ownership and access rights of the token file and its
  308. directory. (TODO: What shall be done if that check fails?)
  309. 1. The server creates a "server token file" containing a "server token" (a
  310. random-generated string of printable ASCII characters) and the IP address
  311. and port where the server listens on. This file can only be read by
  312. client programs that run with the same user rights.
  313. 2. The client checks the path, reads the "server token" from the file and
  314. authenticates itself to the server in each JSON RPC call with that "server
  315. token".
  316. ### Callbacks / Event delivery
  317. p≡p applications must register callback handlers at the Engine. At the moment
  318. there are these callbacks:
  319. * `PEP_STATUS messageToSend(message* msg)`
  320. * `PEP_STATUS notifyHandshake(pEp_identity* self, pEp_identity* partner, sync_handshake_signal signal)`
  321. The JSON adapter register its own functions at the Engine which propagate these
  322. events to all connected clients.
  323. The event propagation to the clients are done via long polling: Clients
  324. call the function `pollForEvents()` that blocks until an event
  325. from the Engine arrives. TODO: remove create_session(), use client ID instead?
  326. It is planned to switch to use WebSockets: In fact this is also a type of
  327. "long polling" and an open TCP connection, opened by the Client.
  328. See: https://pep.foundation/jira/browse/JSON-128
  329. ## Extending / customizing
  330. If you want to extend or customize the p≡p JSON Adapter, there are several
  331. rules and definitions to take into account.
  332. ### API Functions
  333. * The `FunctionMap function` in `ev_server.cc` defines which functions
  334. are callable via the JSON-RPC interface. The existing entries show the
  335. syntax of that map.
  336. Non-static member functions can be called, too. Thanks to `std::function<>`
  337. a member function `Foo::func(Params...)` is handled like a free-standing
  338. function `func(Foo* f, Params...)`.
  339. * For each type there must exist specializations of the template classes
  340. "In" (for input parameters) and "Out" (for output parameters).
  341. The linker will tell you, which specializations are needed.
  342. * The specializations for "generic types" are in `function_map.cc`.
  343. * The specializations for "p≡p-specific types" are in `pep-types.cc`.
  344. #### Parameter directions (In, Out, InOut)
  345. The p≡p JSON Server Adapter supports Input, Output and two ways of "In/Out"
  346. parameters. You have to annotate the direction in the FunctionMap with
  347. `In<>` for input, `Out<>` for output and `InOut<>` or `InOutP<>` for in/out
  348. parameters. These wrapper classes have an optional second template
  349. parameter (parameter type flag) that is explained below.
  350. Return values are always "output" parameters, so they don't have to be
  351. wrapped with `Out<>`, but this wrapper is necessary when you need
  352. non-default wrapper semantics, see below.
  353. Input parameters of fundamental or simple struct types are
  354. usually by-value parameters. Complex structs (or structs that are only
  355. forward-declared in the public API) are usually pointer
  356. parameters. Both ways are supported. You have to specialize `In<T>` or
  357. `In<T*>`, depending how your type is used.
  358. Output parameters of fundamental or simple struct types `T` are usually
  359. declared as a paremeter of type `T*`. The p≡p JSON Server Adapter manages
  360. the memory allocated by the called C function automatically and calls the
  361. appropriate de-allocating function after use.
  362. Calling a function with output parameters requires a dummy value (`null` or
  363. empty string is fine) at the JSON side for each output parameter to keep the
  364. number of parameters at the JSON side the same with the C side.
  365. For In/Out parameters there exist two calling conventions for
  366. call-by-pointer types:
  367. 1. caller allocates object and fills with input values, callee can only *change members*.
  368. The C type of the parameter is usually `struct T*`. Use the wrapper `InOut<T*>`
  369. for these parameters.
  370. 2. caller allocates object and fills with input values, callee might
  371. change/reallocate the *whole object*. The C type of the parameter is
  372. `struct T**`. Use the wrapper `InOutP<T*>` in these cases.
  373. `InOutP<T>` is also the right wrapper for in/out parameters of fundamental or
  374. enum types due to the additional indirection in the C function call
  375. signature.
  376. #### Parameter type flags
  377. The wrapper classes might be instantiated with special "parameter type
  378. flags". If no flag is given the `DefaultFlag` is used with means the
  379. semantics described already above.
  380. At the moment there exist two parameter type flags which are interpreted as
  381. bitfield, so they can be combined:
  382. * NoInput : This denotes a parameter at the C side that shall *not be exposed*
  383. at the JSON side. So the value cannot be specified by the client, it is
  384. provided by the JSON Server Adapter internally (e.g. for PEP_SESSION)
  385. * DontOwn : Used for pointer types who don't "own" the referred ressource,
  386. so it is not released automatically by the JSON Server Adapter after the
  387. call.
  388. More flags will be added when different semantics will be needed.
  389. #### Automatic parameter value generation
  390. For some parameters or parameter combinations the JSON Server Adapter is
  391. able to generate the values automatically either from the environment or
  392. from other parameters.
  393. These automatic parameter value generators are supported at the moment:
  394. ##### In<c_string> and InLength
  395. For functions that have a string parameter of type `const char*` followed by
  396. a `size_t` that specifies the length of the string, the JSON Adapter can
  397. calculate the value of that length parameter automatically, because in the
  398. JSON API the lengths of strings are always known.
  399. Moreover, the "length" that has to be given here means the length of the
  400. string seen by the C API side after processing of all JSON escaping
  401. mechanisms as raw UTF-8 NFC string, so it might be difficult to calculate
  402. that value at client side.
  403. The "magic" is done inside the In<c_string> constructor that stores the string
  404. length in its "Context", and the InLength<> constructore retrieves the value
  405. from its "Context".
  406. Example:
  407. ```
  408. // C function declaration:
  409. char* tohex(const char* input, size_t length);
  410. // API definition:
  411. // with implicit length parameter, with dummy JSON parameter
  412. FP( "tohex", new Func<char*, In<c_string>, InLength<>>( &tohex ))
  413. ```
  414. To be compatible with previous API versions the `InLength` parameter still
  415. needs a dummy placeholder in the JSON interface, but its value is no longer
  416. relevant:
  417. ```
  418. {"jsonrpc":"2.0", "id":28,
  419. "method":"tohex", "params":["some string","dummy_parameter"]
  420. }
  421. ```
  422. It is possible to specifiy `InLength<ParamFlag::NoInput>` so no
  423. parameter is exposed to the JSON API anymore:
  424. ```
  425. FP( "tohex", new Func<char*, In<c_string>, InLength<ParamFlag::NoInput>>( &tohex ))
  426. ```
  427. Now the 2nd parameter is omitted:
  428. ```
  429. {"jsonrpc":"2.0", "id":28,
  430. "method":"tohex", "params":["some string"]
  431. }
  432. ```
  433. ### Embedding in other (desktop) adapters
  434. The JSON Adapter can run as a stand-alone program (called the "mini-adapter") or
  435. as part of another desktop adapter to enhance that adapter with a JSON-RPC interface.
  436. For this the JSON Adapter has to co-operate with the desktop adapter in several ways:
  437. * Startup, configuration and shutdown is managed by the desktop adapter.
  438. * Handshake events and sync messages created by the pEpEngine have to be dispatched
  439. to *all* connected clients, no matter whether they are JSON clients or "native"
  440. clients of the desktop adapter. See "messageToSend" and "notifyHandshake" callbacks.
  441. * The sync thread loop has to be managed by the desktop adapter. The libpEpAdapter
  442. contains an example implementation for that.
  443. * (something else?)
  444. ## TODOs
  445. The following issues are planned but not yet implemented.
  446. * More sensible unit tests
  447. * Generate all the tedious boiler plate code
  448. * the content of pep-types.cc
  449. * perhaps the FunctionMap 'function' in mt-server.cc
  450. * perhaps the JavaScript side of the HTML test page to ensure to be
  451. consistent with the server side in pep-types.cc
  452. * Adapt the "p≡p Transport API", when it is final. (either manually or by
  453. code generator, if ready)
  454. ## Appendix A: Attack scenarios on the authentication
  455. Let's discuss different attack / threat scenarios. I don't know which are
  456. realistic or possible, yet.
  457. ### General ideas / improvements
  458. Currently the JSON Server Adapter writes its server token file in a
  459. directory that is only readable & writable by the user itself.
  460. The server token file is written in $HOME/.pEp/json-token on
  461. UNIX/Linux/MacOS and %LOCALAPPDATA%/pEp/json-token on MS Windows.
  462. The JSON Server Adapter also checks whether .pEp has 0700 access rights
  463. on unixoid systems.
  464. ### Attacker with the same user rights
  465. If the attacker is able to run his malicious code with the same user
  466. rights as the JSON Server Adapter and his legitimate client, it is (and
  467. always will be) *impossible* to prevent this attack. Such an attacker also
  468. can just start a legitimate client that is under his control.
  469. The same applies to an attacker who gains root / admin access rights.
  470. ### Fake Server with different user rights
  471. ```
  472. ,----------. ,--------.
  473. | Attacker | <==> | Client |
  474. `----------' `--------'
  475. ```
  476. If no real JSON Adapter runs an attacker can create a fake server that
  477. pretends to be a legitimate JSON Adapter. It creates its own server token
  478. file, with different and conspicuous access rights, but a limited
  479. JavaScript client might be unable to detect the file permissions.
  480. This fake server cannot access the private key of the user but it might
  481. get sensitive plaintext data the client wants to encrypt. The fake server
  482. cannot sign the encrypted data so the fake would be conspicuous, too. But
  483. that would be too late, because the sensitive plaintext data could
  484. already be leaked by the fake server.
  485. This attack needs a user's home directory that is writable by someone else
  486. (to create a ~/.pEp/ directory) or a foreign-writable ~/.pEp/ directory.
  487. The pEpEngine creates a ~/.pEp/ directory (if not yet exists) and sets the
  488. permissions to 0700 explicitly.
  489. ### Man-in-the-middle with different user rights
  490. ```
  491. ,---------------------. ,----------. ,--------.
  492. | JSON Server Adapter | <==> | Attacker | <==> | Client |
  493. `---------------------' `----------' `--------'
  494. ```
  495. * The attacker cannot read "client token file" nor "server token file".
  496. * The server cannot check "who" connects to it, until the client
  497. authenticates itself, which might be relayed by the attacker from the
  498. original client.
  499. * The attacker has to convince the client that it is a legitimate server. It
  500. has to create a fake "server token file" to divert the client to the
  501. attacker's port. But that fake file cannot contain the right server token
  502. because the attacker does not know it.
  503. * if the server started before the attacker the "server token file"'s
  504. access rights should prevent this (no write access for the attacker, no
  505. "delete" right in common TEMP dir (sticky bit on the directory)
  506. * if the attacker starts before the server it can write a fake toke file.
  507. The server could detect it but is unable to notice the legitimate
  508. client. The client could detect it when it can check the file access
  509. rights.
  510. There might be race conditons...
  511. * Is it possible for the attacker to let the client send the right server
  512. token to him, at least temporarily (e.g. within a race condition)?
  513. * As long as the server runs, the attacker cannot bind to the same address
  514. & port. Finding and binding of the port is done by the server before the
  515. server token file is created and filled.
  516. * When the server that created the "server token file" dies, its port
  517. becomes available for the attacker, but the server token is no longer
  518. valid and no longer useful for the attacker.
  519. * there _might_ be a very _small_ chance for a race condition:
  520. 1. The attacker opens a connection to the running server but does not
  521. use it. To find the server it cannot read the server configuration
  522. file, but it can ask the OS for ports that are open in "listen" mode.
  523. Normally the JSON Adapter listens on 4223 or some port numbers above
  524. that. That means: guessing the server's address is quite easy.
  525. 2. when the server shuts down, the attacker immediately binds itself to
  526. that port. If a client connects just in this moment it sends the server
  527. token to the attacker, not to the server. But the attacker can use that
  528. token now to the server via the already opened TCP connection.
  529. 3. To prevent this the server should call shutdown(2) on its listening
  530. socket to block any new client connection, but still block the port.
  531. (is that the case on all platforms?) Than close(2) all TCP connections
  532. to the clients (if any) and than also delete the server token file.
  533. Finally call close(2) on the listening socket.