summaryrefslogtreecommitdiff
path: root/lcrypt/lcrypt.c
blob: d757f11291e1d0cdd9e8249568a0878b60b560a1 (plain)
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
//  gcc -Wall -O3 -shared -fPIC -DLITTLE_ENDIAN -DLTM_DESC -DLTC_SOURCE -DUSE_LTM -I/usr/include/tomcrypt -I/usr/include/tommath -lz -lutil -ltomcrypt -ltommath lcrypt.c -o /usr/lib64/lua/5.1/lcrypt.so
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/time.h>
#include <zlib.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include <tomcrypt.h>
#include <termios.h>

#ifdef USE_NCIPHER
  #include "ncipher.h"
  extern NFastApp_Connection nfast_conn;
  extern NFast_AppHandle nfast_app;
#else
  #include <pty.h>
#endif

#define likely(x)       __builtin_expect((x),1)
#define unlikely(x)     __builtin_expect((x),0)

#define ADD_FUNCTION(L,name) { lua_pushstring(L, #name); lua_pushcfunction(L, lcrypt_ ## name); lua_settable(L, -3); }
#define ADD_CONSTANT(L,name) { lua_pushstring(L, #name); lua_pushinteger(L, name); lua_settable(L, -3); }

static void lcrypt_error(lua_State *L, int err, void *tofree)
{
  if(unlikely(err != CRYPT_OK))
  {
    if(tofree != NULL) free(tofree);
    lua_pushstring(L, error_to_string(err));
    (void)lua_error(L);
  }
}

static void* lcrypt_malloc(lua_State *L, size_t size)
{
  void *ret = malloc(size);
  if(unlikely(ret == NULL))
  {
    lua_pushstring(L, "Out of memory");
    (void)lua_error(L);
  }
  memset(ret, 0, size);
  return ret;
}

#include "lcrypt_ciphers.c"
#include "lcrypt_hashes.c"
#include "lcrypt_math.c"
#include "lcrypt_bits.c"

static int lcrypt_tohex(lua_State *L)
{
  const char digits[] = "0123456789ABCDEF";
  size_t in_length = 0, spacer_length = 0, prepend_length = 0;
  const unsigned char *in;
  const char *spacer, *prepend;
  int i, j, pos = 0;
  if(unlikely(lua_isnil(L, 1))) { lua_pushlstring(L, "", 0); return 1; }
  in = (const unsigned char*)luaL_checklstring(L, 1, &in_length);
  if(unlikely(in_length == 0)) { lua_pushlstring(L, "", 0); return 1; }
  spacer = luaL_optlstring(L, 2, "", &spacer_length);
  prepend = luaL_optlstring(L, 3, "", &prepend_length);
  char *result = lcrypt_malloc(L, prepend_length + in_length * 2 + (in_length - 1) * spacer_length);
  for(j = 0; j < (int)prepend_length; j++) result[pos++] = prepend[j];
  result[pos++] = digits[(*in >> 4) & 0x0f];
  result[pos++] = digits[*in++ & 0x0f];
  for(i = 1; i < (int)in_length; i++)
  {
    for(j = 0; j < (int)spacer_length; j++) result[pos++] = spacer[j];
    result[pos++] = digits[(*in >> 4) & 0x0f];
    result[pos++] = digits[*in++ & 0x0f];
  }
  lua_pushlstring(L, result, pos);
  free(result);
  return 1;
}

static int lcrypt_fromhex(lua_State *L)
{
  size_t in_length;
  const unsigned char *in = (const unsigned char*)luaL_checklstring(L, 1, &in_length);
  unsigned char result[in_length];
  int i, d = -1, e = -1, pos = 0;
  for(i = 0; i < (int)in_length; i++)
  {
    if(d == -1)
    {
      if(*in >= '0' && *in <= '9')
        d = *in - '0';
      else if(*in >= 'A' && *in <= 'F')
        d = *in - 'A' + 10;
      else if(*in >= 'a' && *in <= 'f')
        d = *in - 'a' + 10;
    }
    else if(e == -1)
    {
      if(*in >= '0' && *in <= '9')
        e = *in - '0';
      else if(*in >= 'A' && *in <= 'F')
        e = *in - 'A' + 10;
      else if(*in >= 'a' && *in <= 'f')
        e = *in - 'a' + 10;
    }
    if(d >= 0 && e >= 0)
    {
      result[pos++] = d << 4 | e;
      d = e = -1;
    }
    in++;
  }
  lua_pushlstring(L, (char*)result, pos);
  return 1;
}

static int lcrypt_compress(lua_State *L)
{
  int err;
  size_t inlen;
  const unsigned char *in = (const unsigned char*)luaL_checklstring(L, 1, &inlen);
  uLongf outlen = compressBound(inlen);
  unsigned char *out = lcrypt_malloc(L, outlen);
  if(unlikely((err = compress(out, &outlen, in, inlen)) != Z_OK))
  {
    free(out);
    lua_pushstring(L, zError(err));
    return lua_error(L);
  }
  lua_pushlstring(L, (char*)out, outlen);
  free(out);
  return 1;
}

static int lcrypt_uncompress(lua_State *L)
{
  int i, err;
  size_t inlen;
  const unsigned char *in = (const unsigned char*)luaL_checklstring(L, 1, &inlen);
  uLongf outlen = inlen << 1;
  unsigned char *out = NULL;
  for(i = 2; i < 16; i++)
  {
    out = lcrypt_malloc(L, outlen);
    if(likely((err = uncompress(out, &outlen, in, inlen)) == Z_OK)) break;
    if(unlikely(err != Z_BUF_ERROR))
    {
      free(out);
      lua_pushstring(L, zError(err));
      return lua_error(L);
    }
    free(out);
    outlen = inlen << i;
  }
  if(unlikely(err == Z_BUF_ERROR))
  {
    free(out);
    lua_pushstring(L, zError(err));
    return lua_error(L);
  }
  lua_pushlstring(L, (char*)out, outlen);
  free(out);
  return 1;
}

static int lcrypt_base64_encode(lua_State *L)
{
  size_t inlen;
  const unsigned char *in = (const unsigned char*)luaL_checklstring(L, 1, &inlen);
  unsigned long outlen = (inlen + 3) * 4 / 3;
  unsigned char *out = malloc(outlen);
  if(out == NULL) return 0;
  lcrypt_error(L, base64_encode(in, inlen, out, &outlen), out);
  lua_pushlstring(L, (char*)out, outlen);
  free(out);
  return 1;
}

static int lcrypt_base64_decode(lua_State *L)
{
  size_t inlen;
  const unsigned char *in = (const unsigned char*)luaL_checklstring(L, 1, &inlen);
  unsigned long outlen = inlen * 3 / 4;
  unsigned char *out = malloc(outlen);
  if(out == NULL) return 0;
  lcrypt_error(L, base64_decode(in, inlen, out, &outlen), out);
  lua_pushlstring(L, (char*)out, outlen);
  free(out);
  return 1;
}

static int lcrypt_xor(lua_State *L)
{
  int i;
  size_t a_length, b_length;
  const unsigned char *a = (const unsigned char*)luaL_checklstring(L, 1, &a_length);
  const unsigned char *b = (const unsigned char*)luaL_checklstring(L, 2, &b_length);
  unsigned char *c = NULL;
  if(a_length > b_length)
  {
    size_t temp = a_length;
    a_length = b_length;
    b_length = temp;
    c = (void*)a; a = b; b = c;
  }
  c = lcrypt_malloc(L, b_length);
  for(i = 0; i < a_length; i++) c[i] = a[i] ^ b[i];
  for(; i < b_length; i++) c[i] = b[i];
  lua_pushlstring(L, (char*)c, b_length);
  free(c);
  return 1;
}

static int lcrypt_sleep(lua_State *L)
{
  usleep(1000000.0 * luaL_checknumber(L, 1));
  return(0);
}

static int lcrypt_time(lua_State *L)
{
  double ret;
  struct timeval tv;
  gettimeofday(&tv, NULL);
  ret = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
  lua_pushnumber(L, ret);
  return(1);
}

static int lcrypt_random(lua_State *L)
{
  int len = luaL_checkint(L, 1);
  #ifdef USE_NCIPHER
    M_Command command;
    M_Reply reply;
    M_Status rc;
    memset(&command, 0, sizeof(command));
    memset(&reply, 0, sizeof(reply));
    command.cmd = Cmd_GenerateRandom;
    command.args.generaterandom.lenbytes = len;
    if(unlikely((rc = NFastApp_Transact(nfast_conn, NULL, &command, &reply, NULL)) != Status_OK))
    {
      lua_pushstring(L, NF_Lookup(rc, NF_Status_enumtable));
      (void)lua_error(L);
    }
    if(unlikely(reply.status != Status_OK))
    {
      lua_pushstring(L, NF_Lookup(reply.status, NF_Status_enumtable));
      (void)lua_error(L);
    }
    if(unlikely(len != reply.reply.generaterandom.data.len))
    {
      lua_pushstring(L, "Wrong length returned");
      (void)lua_error(L);
    }
    lua_pushlstring(L, reply.reply.generaterandom.data.ptr, len);
    NFastApp_Free_Reply(nfast_app, NULL, NULL, &reply);
  #else
    FILE *fp;
    char *buffer = lcrypt_malloc(L, len);
    if(unlikely((fp = fopen("/dev/urandom", "rb")) == NULL))
    {
      lua_pushstring(L, "Unable to open /dev/urandom.");
      (void)lua_error(L);
    }
    if(unlikely(fread(buffer, len, 1, fp) != 1))
    {
      fclose(fp);
      lua_pushstring(L, "Unable to read /dev/urandom.");
      (void)lua_error(L);
    }
    fclose(fp);
    lua_pushlstring(L, buffer, len);
    free(buffer);
  #endif
  return 1;
}

static FILE *lgetfile(lua_State *L, int index)
{
  FILE **fp = lua_touserdata(L, index);
  if(unlikely(fp == NULL)) return NULL;
  if(lua_getmetatable(L, index))
  {
    lua_getfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE);
    if(lua_rawequal(L, -1, -2))
    {
      lua_pop(L, 2);
      return *fp;
    }
    lua_pop(L, 2);
  }
  return NULL;
}

static int lcrypt_tcsetattr(lua_State* L)
{
  struct termios old, new;
  FILE *fp = lgetfile(L, 1);
  if(unlikely(fp == NULL)) return 0;
  if(unlikely(tcgetattr(fileno(fp), &old) != 0)) return 0;
  new = old;
  new.c_iflag = luaL_optint(L, 2, old.c_iflag);
  new.c_oflag = luaL_optint(L, 3, old.c_oflag);
  new.c_cflag = luaL_optint(L, 4, old.c_cflag);
  new.c_lflag = luaL_optint(L, 5, old.c_lflag);
  if(unlikely(tcsetattr(fileno(fp), TCSAFLUSH, &new) != 0)) return 0;
  lua_pushinteger(L, new.c_iflag);
  lua_pushinteger(L, new.c_oflag);
  lua_pushinteger(L, new.c_cflag);
  lua_pushinteger(L, new.c_lflag);
  return 4;
}

static int lcrypt_flag_add(lua_State *L)
{
  uint32_t a = luaL_checkint(L, 1);
  uint32_t b = luaL_checkint(L, 2);
  lua_pushinteger(L, a | b);
  return 1;
}

static int lcrypt_flag_remove(lua_State *L)
{
  uint32_t a = luaL_checkint(L, 1);
  uint32_t b = luaL_checkint(L, 2);
  lua_pushinteger(L, a & ~b);
  return 1;
}

#ifndef USE_NCIPHER

typedef struct
{
  int fd;
  int pid;
  char *command;
} lcrypt_spawn_t;

static int lcrypt_spawn(lua_State *L)
{
  int fd, pid, argc;
  #define MAX_ARGUMENT 128
  const char *command = luaL_checkstring(L, 1); 
  char *cmd = strdup(command);
  char *pos = cmd, *p;
  char *argv[MAX_ARGUMENT];
  for(argc = 0; argc < MAX_ARGUMENT-1; argc++)
  {
    // eat whitespace
    while(*pos == ' ' || *pos == '\t' || *pos == '\n' || *pos == '\r')
    {
      if(*pos == '\\') for(p = pos; *p != '\0'; p++) *p = *(p + 1);
      pos++;
    }
    // start of argument found
    argv[argc] = pos;
    if(*argv[argc] == '"' || *argv[argc] == '\'') // quoted argument
    {
      pos++;
      while(*pos != *argv[argc] && *pos != '\0')
      {
        if(*pos == '\\') for(p = pos; *p != '\0'; p++) *p = *(p + 1);
        pos++;
      }
      argv[argc]++;
    }
    else // non-quoted argument
    {
      while(*pos != ' ' && *pos != '\t' && *pos != '\n' && *pos != '\r' && *pos != '\0')
      {
        if(*pos == '\\') for(p = pos; *p != '\0'; p++) *p = *(p + 1);
        pos++;
      }
    }
    if(*pos == '\0') break;
    *pos++ = '\0';
  }
  argv[++argc] = NULL;

  errno = 0;
  pid = forkpty(&fd, NULL, NULL, NULL);
  if(pid == 0) // child
  {
    execvp(argv[0], argv);
    // if we get here, it's an error!
    perror("'unable to spawn process");
    return 0;
  }
  else if(errno != 0)
  {
    lua_pushnil(L);
    lua_pushstring(L, strerror(errno));
    return 2;
  }
  else
  {
    lcrypt_spawn_t *lsp = lua_newuserdata(L, sizeof(lcrypt_spawn_t));
    lsp->fd = fd;
    lsp->pid = pid;
    lsp->command = cmd;
    luaL_getmetatable(L, "LSPAWN");
    (void)lua_setmetatable(L, -2);
    return 1;
  }
}

static int lcrypt_spawn_close(lua_State *L)
{
  lcrypt_spawn_t *lsp = (lcrypt_spawn_t*)luaL_checkudata(L, 1, "LSPAWN");
  if(lsp->pid > 0)
  {
    (void)kill(lsp->pid, SIGQUIT);
    lsp->pid = -1;
  }
  if(lsp->fd >= 0)
  {
    (void)close(lsp->fd);
    lsp->fd = -1;
  }
  if(lsp->command != NULL)
  {
    free(lsp->command);
    lsp->command = NULL;
  }
  return 0;
}

static int lcrypt_spawn_read(lua_State *L)
{
  lcrypt_spawn_t *lsp = (lcrypt_spawn_t*)luaL_checkudata(L, 1, "LSPAWN");
  int count = luaL_optint(L, 2, 4096);
  char *buffer;
  if(lsp->fd < 0)
  {
    lua_pushstring(L, "Spawn closed");
    lua_error(L);
    return 0;
  }
  if((buffer = malloc(count)) == NULL)
  {
    lua_pushnil(L);
    lua_pushstring(L, "Unable to allocate memory");
    return 2;
  }
  count = read(lsp->fd, buffer, count);
  if(errno != 0)
  {
    free(buffer);
    lua_pushnil(L);
    lua_pushstring(L, strerror(errno));
    return 2;
  }
  lua_pushlstring(L, buffer, count);
  free(buffer);
  return 1;
}

static int lcrypt_spawn_write(lua_State *L)
{
  lcrypt_spawn_t *lsp = (lcrypt_spawn_t*)luaL_checkudata(L, 1, "LSPAWN");
  size_t in_length = 0;
  const char* in = luaL_checklstring(L, 2, &in_length);
  if(lsp->fd < 0)
  {
    lua_pushstring(L, "closed");
    lua_error(L);
    return 0;
  }
  write(lsp->fd, in, in_length);
  if(errno != 0)
  {
    lua_pushstring(L, strerror(errno));
    return 1;
  }
  return 0;
}

static int lcrypt_spawn_index(lua_State *L)
{
  (void)luaL_checkudata(L, 1, "LSPAWN");
  const char *index = luaL_checkstring(L, 2);
  if(strcmp(index, "read") == 0)
    lua_pushcfunction(L, lcrypt_spawn_read);
  else if(strcmp(index, "write") == 0)
    lua_pushcfunction(L, lcrypt_spawn_write);
  else if(strcmp(index, "close") == 0)
    lua_pushcfunction(L, lcrypt_spawn_close);
  else
    return 0;
  return 1;
}

static const luaL_Reg lcrypt_spawn_flib[] =
{
  {"__gc",  lcrypt_spawn_close},
  {NULL, NULL}
};

#endif

static const luaL_Reg lcryptlib[] =
{
  {"tohex",         lcrypt_tohex},
  {"fromhex",       lcrypt_fromhex},
  {"compress",      lcrypt_compress},
  {"uncompress",    lcrypt_uncompress},
  {"base64_encode", lcrypt_base64_encode},
  {"base64_decode", lcrypt_base64_decode},
  {"xor",           lcrypt_xor},
  {"sleep",         lcrypt_sleep},
  {"time",          lcrypt_time},
  {"random",        lcrypt_random},
  {"tcsetattr",     lcrypt_tcsetattr},
  {"flag_add",      lcrypt_flag_add},
  {"flag_remove",   lcrypt_flag_remove},
  #ifndef USE_NCIPHER
    {"spawn",         lcrypt_spawn},
  #endif
  {NULL, NULL}
};

int luaopen_lcrypt(lua_State *L);
int luaopen_lcrypt(lua_State *L)
{
  luaL_register(L, "lcrypt", lcryptlib);

  #ifndef USE_NCIPHER
    (void)luaL_newmetatable(L, "LSPAWN");
    lua_pushliteral(L, "__index");
    lua_pushcfunction(L, lcrypt_spawn_index);
    lua_rawset(L, -3);
    luaL_register(L, NULL, lcrypt_spawn_flib);
  #endif

  lua_getglobal(L, "lcrypt");

  lcrypt_start_ciphers(L);
  lcrypt_start_hashes(L);
  lcrypt_start_math(L);
  lcrypt_start_bits(L);

  lua_pushstring(L, "iflag");
  lua_newtable(L);
  ADD_CONSTANT(L, IGNBRK);  ADD_CONSTANT(L, BRKINT);  ADD_CONSTANT(L, IGNPAR);  ADD_CONSTANT(L, PARMRK);
  ADD_CONSTANT(L, INPCK);   ADD_CONSTANT(L, ISTRIP);  ADD_CONSTANT(L, INLCR);   ADD_CONSTANT(L, IGNCR);
  ADD_CONSTANT(L, ICRNL);   ADD_CONSTANT(L, IXON);    ADD_CONSTANT(L, IXANY);   ADD_CONSTANT(L, IXOFF);
  lua_settable(L, -3);

  lua_pushstring(L, "oflag");
  lua_newtable(L);
  #ifdef OLCUC
    ADD_CONSTANT(L, OLCUC);
  #endif
  #ifdef OFILL
    ADD_CONSTANT(L, OFILL);
  #endif
  #ifdef OFDEL
    ADD_CONSTANT(L, OFDEL);
  #endif
  #ifdef NLDLY
    ADD_CONSTANT(L, NLDLY);
  #endif
  #ifdef CRDLY
    ADD_CONSTANT(L, CRDLY);
  #endif
  #ifdef TABDLY
    ADD_CONSTANT(L, TABDLY);
  #endif
  #ifdef BSDLY
    ADD_CONSTANT(L, BSDLY);
  #endif
  #ifdef VTDLY
    ADD_CONSTANT(L, VTDLY);
  #endif
  #ifdef FFDLY
    ADD_CONSTANT(L, FFDLY);
  #endif
  ADD_CONSTANT(L, OPOST);   ADD_CONSTANT(L, ONLCR);   ADD_CONSTANT(L, OCRNL);   ADD_CONSTANT(L, ONOCR);
  ADD_CONSTANT(L, ONLRET);
  lua_settable(L, -3);

  lua_pushstring(L, "cflag");
  lua_newtable(L);
  ADD_CONSTANT(L, CS5);     ADD_CONSTANT(L, CS6);     ADD_CONSTANT(L, CS7);     ADD_CONSTANT(L, CS8);
  ADD_CONSTANT(L, CSTOPB);  ADD_CONSTANT(L, CREAD);   ADD_CONSTANT(L, PARENB);  ADD_CONSTANT(L, PARODD);
  ADD_CONSTANT(L, HUPCL);   ADD_CONSTANT(L, CLOCAL);
  lua_settable(L, -3);

  lua_pushstring(L, "lflag");
  lua_newtable(L);
  ADD_CONSTANT(L, ISIG);    ADD_CONSTANT(L, ICANON);  ADD_CONSTANT(L, ECHO);    ADD_CONSTANT(L, ECHOE);
  ADD_CONSTANT(L, ECHOK);   ADD_CONSTANT(L, ECHONL);  ADD_CONSTANT(L, NOFLSH);  ADD_CONSTANT(L, TOSTOP);
  ADD_CONSTANT(L, IEXTEN);
  lua_settable(L, -3);

  lua_pop(L, 1);
  return 1;
}