aboutsummaryrefslogtreecommitdiff
path: root/core.c
blob: 8746ec4f822434f3bfe05ee01f0265fdcd512224 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/*
 * core.c
 * ------
 * This module contains code to probe the FPGA for its installed cores.
 *
 * Author: Paul Selkirk, Rob Austein
 * Copyright (c) 2015, NORDUnet A/S All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * - Neither the name of the NORDUnet nor the names of its contributors may
 *   be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

#include "hal.h"
#include "verilog_constants.h"

/*
 * Each Cryptech core has a set of 4-byte registers, which are accessed
 * through a 16-bit address. The address space is divided as follows:
 *   3 bits segment selector       | up to 8 segments
 *   5 bits core selector          | up to 32 cores/segment (see note below)
 *   8 bits register selector      | up to 256 registers/core (see modexp below)
 *
 * i.e, the address is structured as:
 * sss ccccc rrrrrrrr
 *
 * The I2C and UART communication channels use this 16-bit address format
 * directly in their read and write commands.
 *
 * The EIM communications channel translates this 16-bit address into a
 * 32-bit memory-mapped address in the range 0x08000000..807FFFF:
 * 00001000000000 sss 0 ccccc rrrrrrrr 00
 *
 * EIM, as implemented on the Novena, uses a 19-bit address space:
 *   Bits 18..16 are the semgent selector.
 *   Bits 15..10 are the core selector.
 *   Bits 9..2 are the register selector.
 *   Bits 1..0 are zero, because reads and writes are always word aligned.
 *
 * Note that EIM can support 64 cores per segment, but we sacrifice one bit
 * in order to map it into a 16-bit address space.
 */

/*
 * Structure of our internal database is private, in case we want to
 * be change representation (array, tree, list of lists, whatever) at
 * some later date without having to change the public API.
 */

struct hal_core {
  hal_core_info_t info;
  struct hal_core *next;
};

/*
 * Check whether a core's name matches a particular string.  This is a
 * bit nasty due to non-null-terminated fixed-length names.
 */

static int name_matches(const hal_core_t *const core, const char * const name)
{
  return (core != NULL && name != NULL && *name != '\0' &&
          strncmp(name, core->info.name, strnlen(name, sizeof(core->info.name))) == 0);
}

/*
 * Probe the FPGA and build our internal database.
 *
 * At the moment this knows far more than it should about pecularities
 * of certain cores.  In theory at least some of this will be fixed
 * soon on the Verilog side.  Adding a core-length word to the core
 * header sure would make this simpler.
 */

#define CORE_MIN                0
#define	CORE_MAX                0x10000
#define	CORE_SIZE               0x100

/* Extra space to leave after particular cores.  Yummy. */

static const struct { const char *name; hal_addr_t extra; } gaps[] = {
  { "trng",     4 * CORE_SIZE }, /* Four empty slots after trng */
  { "rosc ent", 3 * CORE_SIZE }, /* Three empty slots after rosc */
  { "csprng",   4 * CORE_SIZE }, /* Four empty slots after csprng */
  { "modexps6", 3 * CORE_SIZE }, /* ModexpS6 uses four slots */
};

static hal_core_t *probe_cores(void)
{
  static hal_core_t *head = NULL;

  if (head != NULL)
    return head;

  hal_core_t **tail = &head;
  hal_core_t *core = NULL;
  hal_error_t err = HAL_OK;

  for (hal_addr_t addr = CORE_MIN; addr < CORE_MAX; addr += CORE_SIZE) {

    if (core == NULL && (core = malloc(sizeof(hal_core_t))) == NULL) {
      err = HAL_ERROR_ALLOCATION_FAILURE;
      goto fail;
    }

    memset(core, 0, sizeof(*core));
    core->info.base = addr;

    if ((err = hal_io_read(core, ADDR_NAME0,   (uint8_t *) core->info.name,    8)) != HAL_OK ||
        (err = hal_io_read(core, ADDR_VERSION, (uint8_t *) core->info.version, 4)) != HAL_OK)
      goto fail;

    if (core->info.name[0] == '\0')
      continue;

    for (int i = 0; i < sizeof(gaps)/sizeof(*gaps); i++) {
      if (name_matches(core, gaps[i].name)) {
        addr += gaps[i].extra;
        break;
      }
    }

    *tail = core;
    tail = &core->next;
    core = NULL;
  }

  if (core != NULL)
    free(core);

  return head;

 fail:
  if (core != NULL)
    free(core);
  while ((core = head) != NULL) {
    head = core->next;
    free(core);
  }
  return NULL;
}

const hal_core_t * hal_core_iterate(const hal_core_t *core)
{
  return core == NULL ? probe_cores() : core->next;
}

const hal_core_t *hal_core_find(const char *name, const hal_core_t *core)
{
  for (core = hal_core_iterate(core); core != NULL; core = core->next)
    if (name_matches(core, name))
      return core;
  return NULL;
}

hal_error_t hal_core_check_name(const hal_core_t **core, const char *name)
{
  if (core == NULL || name == NULL)
    return HAL_ERROR_BAD_ARGUMENTS;

  if (*core == NULL && (*core = hal_core_find(name, NULL)) != NULL)
    return HAL_OK;

  if (*core == NULL || !name_matches(*core, name))
    return HAL_ERROR_CORE_NOT_FOUND;

  return HAL_OK;
}

hal_addr_t hal_core_base(const hal_core_t *core)
{
  return core == NULL ? 0 : core->info.base;
}

const hal_core_info_t *hal_core_info(const hal_core_t *core)
{
  return core == NULL ? NULL : &core->info;
}

/*
 * Local variables:
 * indent-tabs-mode: nil
 * End:
 */
n class="p">(SLIP_END) except tornado.iostream.StreamClosedError: logger.info("RPC UART closed") for q in self.queues.itervalues(): q.put_nowait(None) return logger.debug("RPC recv: %s", ":".join("{:02x}".format(ord(c)) for c in reply)) if reply == SLIP_END: continue try: handle = client_handle_get(slip_decode(reply)) except: logger.debug("RPC skipping bad packet") continue if handle not in self.queues: logger.debug("RPC ignoring response: handle 0x%x", handle) continue logger.debug("RPC queue put: handle 0x%x, qsize %s", handle, self.queues[handle].qsize()) self.queues[handle].put_nowait(reply) def logout_all(self): "Execute an RPC LOGOUT_ALL operation." return self.rpc_input(slip_encode(logout_all_msg)) class QueuedStreamClosedError(tornado.iostream.StreamClosedError): "Deferred StreamClosedError passed throught a Queue." class RPCServer(PFUnixServer): """ Serve multiplexed Cryptech RPC over a PF_UNIX socket. """ @tornado.gen.coroutine def handle_stream(self, stream, address): "Handle one network connection." handle = self.next_client_handle() queue = tornado.queues.Queue() logger.info("RPC connected %r, handle 0x%x", stream, handle) while True: try: logger.debug("RPC socket read, handle 0x%x", handle) query = yield stream.read_until(SLIP_END) if len(query) < 9: continue query = slip_encode(client_handle_set(slip_decode(query), handle)) yield self.serial.rpc_input(query, handle, queue) logger.debug("RPC queue wait, handle 0x%x", handle) reply = yield queue.get() if reply is None: raise QueuedStreamClosedError() logger.debug("RPC socket write, handle 0x%x", handle) yield stream.write(SLIP_END + reply) except tornado.iostream.StreamClosedError: logger.info("RPC closing %r, handle 0x%x", stream, handle) stream.close() query = slip_encode(client_handle_set(logout_msg, handle)) yield self.serial.rpc_input(query, handle) return client_handle = int(time.time()) << 4 @classmethod def next_client_handle(cls): cls.client_handle += 1 cls.client_handle &= 0xFFFFFFFF return cls.client_handle class CTYIOStream(SerialIOStream): """ Tornado IOStream for a serial console channel. """ def __init__(self, device, console_log = None): super(CTYIOStream, self).__init__(device) self.attached_cty = None self.console_log = console_log @tornado.gen.coroutine def cty_output_loop(self): while True: try: buffer = yield self.read_bytes(self.read_chunk_size, partial = True) except tornado.iostream.StreamClosedError: logger.info("CTY UART closed") if self.attached_cty is not None: self.attached_cty.close() return try: futures = [] if self.console_log is not None: futures.append(self.console_log.write(buffer)) if self.attached_cty is not None: futures.append(self.attached_cty.write(buffer)) if futures: yield futures except tornado.iostream.StreamClosedError: pass class CTYServer(PFUnixServer): """ Serve Cryptech console over a PF_UNIX socket. """ @tornado.gen.coroutine def handle_stream(self, stream, address): "Handle one network connection." if self.serial.attached_cty is not None: yield stream.write("[Console already in use, sorry]\n") stream.close() return logger.info("CTY connected to %r", stream) try: self.serial.attached_cty = stream while self.serial.attached_cty is stream: yield self.serial.write((yield stream.read_bytes(1024, partial = True))) except tornado.iostream.StreamClosedError: stream.close() finally: logger.info("CTY disconnected from %r", stream) if self.serial.attached_cty is stream: self.serial.attached_cty = None class ProbeIOStream(SerialIOStream): """ Tornado IOStream for probing a serial port. This is nasty. """ def __init__(self, device): super(ProbeIOStream, self).__init__(device) @classmethod @tornado.gen.coroutine def run_probes(cls, args): if args.rpc_device is not None and args.cty_device is not None: return if args.probe: devs = set(args.probe) else: devs = set(str(port) for port, desc, hwid in serial.tools.list_ports_posix.comports() if "VID:PID=0403:6014" in hwid) devs.discard(args.rpc_device) devs.discard(args.cty_device) if not devs: return logging.debug("Probing candidate devices %s", " ".join(devs)) results = yield dict((dev, ProbeIOStream(dev).run_probe()) for dev in devs) for dev, result in results.iteritems(): if result == "cty" and args.cty_device is None: logger.info("Selecting %s as CTY device", dev) args.cty_device = dev if result == "rpc" and args.rpc_device is None: logger.info("Selecting %s as RPC device", dev) args.rpc_device = dev @tornado.gen.coroutine def run_probe(self): RPC_query = struct.pack(">LL", RPC_FUNC_GET_VERSION, 0) RPC_reply = struct.pack(">LLL", RPC_FUNC_GET_VERSION, 0, HAL_OK) probe_string = SLIP_END + Control_U + SLIP_END + RPC_query + SLIP_END + Control_U + Control_M yield self.write(probe_string) yield tornado.gen.sleep(0.5) response = yield self.read_bytes(self.read_chunk_size, partial = True) logger.debug("Probing %s: %r %s", self.serial_device, response, ":".join("{:02x}".format(ord(c)) for c in response)) is_cty = any(prompt in response for prompt in ("Username:", "Password:", "cryptech>")) try: is_rpc = response[response.index(SLIP_END + RPC_reply) + len(SLIP_END + RPC_reply) + 4] == SLIP_END except ValueError: is_rpc = False except IndexError: is_rpc = False assert not is_cty or not is_rpc result = None if is_cty: result = "cty" yield self.write(Control_U) if is_rpc: result = "rpc" yield self.write(SLIP_END) self.close() raise tornado.gen.Return(result) @tornado.gen.coroutine def main(): parser = argparse.ArgumentParser(formatter_class = argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("-v", "--verbose", action = "count", help = "blather about what we're doing") parser.add_argument("-l", "--log-file", help = "log to file instead of stderr") parser.add_argument("-L", "--console-log", type = argparse.FileType("a"), help = "log console output to file") parser.add_argument("-p", "--probe", nargs = "*", metavar = "DEVICE", help = "probe for device UARTs") parser.add_argument("--rpc-device", help = "RPC serial device name", default = os.getenv("CRYPTECH_RPC_CLIENT_SERIAL_DEVICE")) parser.add_argument("--rpc-socket", help = "RPC PF_UNIX socket name", default = os.getenv("CRYPTECH_RPC_CLIENT_SOCKET_NAME", "/tmp/.cryptech_muxd.rpc")) parser.add_argument("--cty-device", help = "CTY serial device name", default = os.getenv("CRYPTECH_CTY_CLIENT_SERIAL_DEVICE")) parser.add_argument("--cty-socket", help = "CTY PF_UNIX socket name", default = os.getenv("CRYPTECH_CTY_CLIENT_SOCKET_NAME", "/tmp/.cryptech_muxd.cty")) args = parser.parse_args() if args.log_file is not None: logging.getLogger().handlers[:] = [logging.handlers.WatchedFileHandler(args.log_file)] logging.getLogger().handlers[0].setFormatter( logging.Formatter("%(asctime)-15s %(name)s[%(process)d]:%(levelname)s: %(message)s", "%Y-%m-%d %H:%M:%S")) if args.verbose: logging.getLogger().setLevel(logging.DEBUG if args.verbose > 1 else logging.INFO) if args.probe is not None: yield ProbeIOStream.run_probes(args) if args.console_log is not None: console_log = tornado.iostream.PipeIOStream(args.console_log.fileno()) else: console_log = None futures = [] if args.rpc_device is None: logger.warn("No RPC device found") else: rpc_stream = RPCIOStream(device = args.rpc_device) rpc_server = RPCServer(rpc_stream, args.rpc_socket) futures.append(rpc_stream.rpc_output_loop()) futures.append(rpc_stream.logout_all()) if args.cty_device is None: logger.warn("No CTY device found") else: cty_stream = CTYIOStream(device = args.cty_device, console_log = console_log) cty_server = CTYServer(cty_stream, args.cty_socket) futures.append(cty_stream.cty_output_loop()) # Might want to use WaitIterator(dict(...)) here so we can # diagnose and restart output loops if they fail? if futures: yield futures if __name__ == "__main__": try: tornado.ioloop.IOLoop.current().run_sync(main) except (SystemExit, KeyboardInterrupt): pass except: logger.exception("Unhandled exception") else: logger.debug("Main loop exited")