Exemplo n.º 1
0
static void
lib_md_init(mrb_state *mrb, struct mrb_md *md, int type)
{
  int ctxsize;

  ctxsize = md_ctx_size(type);
  if (ctxsize == 0) {
    mrb_raise(mrb, E_NOTIMP_ERROR, "not supported");
  }
  md->type = type;
  md->ctx = NULL;
  md->ctx = mrb_malloc(mrb, ctxsize);
  md_init(type, md->ctx);
}
Exemplo n.º 2
0
track_t *track_alloc(const char *fn)
{
    track_t *track = (track_t *)malloc(sizeof(track_t));

    str_init(&track->fn);
    str_puts(&track->fn, fn);

    md_init(&track->md);
    au_init(&track->au);

    track->avail = false; /* track is unavailable until its format is found */
    track->sane = true; /* track is sane until decoding it fails */
    
    return track;
}
Exemplo n.º 3
0
/*
 * generate new key from all the pools
 */
static void
reseed(FState * st)
{
    unsigned	k;
    unsigned	n;
    MD_CTX		key_md;
    unsigned char	buf[BLOCK];

    /* set pool as empty */
    st->pool0_bytes = 0;

    /*
     * Both #0 and #1 reseed would use only pool 0. Just skip #0 then.
     */
    n = ++st->reseed_count;

    /*
     * The goal: use k-th pool only 1/(2^k) of the time.
     */
    md_init(&key_md);
    for (k = 0; k < NUM_POOLS; k++)
    {
	md_result(&st->pool[k], buf);
	md_update(&key_md, buf, BLOCK);

	if (n & 1 || !n)
	    break;
	n >>= 1;
    }

    /* add old key into mix too */
    md_update(&key_md, st->key, BLOCK);

    /* add pid to make output diverse after fork() */
    md_update(&key_md, (const unsigned char *)&st->pid, sizeof(st->pid));

    /* now we have new key */
    md_result(&key_md, st->key);

    /* use new key */
    ciph_init(&st->ciph, st->key, BLOCK);

    memset(&key_md, 0, sizeof(key_md));
    memset(buf, 0, BLOCK);
}
Exemplo n.º 4
0
/*
 * generate new key from all the pools
 */
static void reseed(FState *st)
{
	unsigned k;
	unsigned n;
	mdCtx key_md;
	uint8_t buf[block];

	/* set pool as empty */
	st->pool0Bytes = 0;

	/*
	 * Both #0 and #1 reseed would use only pool 0. Just skip #0 then.
	 */
	n = ++st->reseedCount;

	/*
	 * The goal: use k-th pool only 1/(2^k) of the time.
	 */
	md_init(&key_md);
	for (k = 0; k < numPools; k++) {
		md_result(&st->pool[k], buf);
		md_update(&key_md, buf, block);

		if (n & 1 || !n)
			break;
		n >>= 1;
	}

	/* add old key into mix too */
	md_update(&key_md, st->key, block);

	/* now we have new key */
	md_result(&key_md, st->key);

	/* use new key */
	ciph_init(&st->ciph, st->key, block);

	memset(&key_md, 0, sizeof(key_md));
	memset(buf, 0, block);
}
Exemplo n.º 5
0
// program execution starts here!
int main( int argc, char** argv ) {
   curl_global_init(CURL_GLOBAL_ALL);

   // start up protocol buffers
   GOOGLE_PROTOBUF_VERIFY_VERSION;
   
   g_config_file = strdup( METADATA_DEFAULT_CONFIG );
   
   // process command-line options
   int c;
   int rc;
   bool make_daemon = true;
   bool good_input = true;
   char* mc_root = NULL;
   char* logfile = NULL;
   char* pidfile = NULL;
   int portnum = 0;
   int reload_pid = 0;
   
   while((c = getopt(argc, argv, "fc:m:p:u:l:P:k:")) != -1) {
      switch( c ) {
         case 'f': {
            make_daemon = false;
            break;
         }
         case '?': {
            usage( argv[0], 1 );
         }
         case 'c': {
            g_config_file = realpath( optarg, NULL );
            break;
         }
         case 'm': {
            mc_root = realpath( optarg, NULL );
            break;
         }
         case 'P': {
            portnum = strtol( optarg, NULL, 10 );
            if( portnum <= 0 )
               good_input = false;
            break;
         }
         case 'u': {
            g_secrets_file = realpath( optarg, NULL );
            break;
         }
         case 'l': {
            logfile = strdup( optarg );
            break;
         }
         case 'p': {
            pidfile = realpath( optarg, NULL );
            break;
         }
         case 'k': {
            reload_pid = strtol( optarg, NULL, 10 );
            if( reload_pid <= 0 )
               good_input = false;
            break;
         }
         default: {
            fprintf(stderr, "Ignoring unrecognized option %c\n", c);
            good_input = false;
            break;
         }
      }
   }
   
   if( !good_input ) {
      usage( argv[0], 1 );
   }

   if( reload_pid > 0 ) {
      // all we're doing is telling a running metadata server to reload
      kill( reload_pid, SIGUSR1 );
      exit(0);
   }
   
   // read the config
   struct md_syndicate_conf conf;
   g_conf = &conf;

   dbprintf("reading config %s\n", g_config_file);
   if( md_read_conf( g_config_file, &conf ) != 0 ) {
      errorf("Could not read config at %s\n", g_config_file);
      usage( argv[0], 1 );
   }
   
   // user-given portnum?
   if( portnum > 0 ) {
      conf.portnum = portnum;
   }
   if( conf.portnum == 0 ) {
      errorf("Invalid port number %d.  Specify PORTNUM in the config file or pass -p\n", conf.portnum);
      exit(1);
   }
   
   // master copy supplied in args?
   if( mc_root ) {
      if( conf.master_copy_root ) {
         free( conf.master_copy_root );
      }
      conf.master_copy_root = mc_root;
   }
   
   // secrets file supplied in args?
   if( g_secrets_file ) {
      if( conf.secrets_file ) {
         free( conf.secrets_file );
      }
      conf.secrets_file = g_secrets_file;
   }
   else if( conf.secrets_file ) {
      g_secrets_file = strdup( conf.secrets_file );
   }
  
   // pidfile supplied in args?
   if( pidfile ) {
      if( conf.md_pidfile_path ) {
         free( conf.md_pidfile_path );
      }
      conf.md_pidfile_path = pidfile;
   }

   dbprintf("%s", "initializing libsyndicate\n");
   
   // set the config
   if( md_init( &conf, NULL ) != 0 )
      exit(1);
   
   md_connect_timeout( conf.query_timeout );
   md_signals( 0 );        // no signals

   dbprintf("reading users file %s\n", conf.secrets_file );

   // read the users file
   struct md_user_entry **users = NULL;
   if( conf.secrets_file ) {
      users = md_parse_secrets_file( conf.secrets_file );
      if( users == NULL ) {
         exit(1);
      }
   }
   else {
      errorf("No secrets file given.  Pass -u or specify a value for %s in the config\n", SECRETS_FILE_KEY );
      usage( argv[0], 1 );
   }

   // need to daemonize?
   if( make_daemon ) {
      FILE* log = NULL;
      rc = md_daemonize( logfile, conf.md_pidfile_path, &log );
      if( rc < 0 ) {
         errorf("md_daemonize rc = %d\n", rc );
         exit(1);
      }

      if( log )
         conf.md_logfile = log;
   }

   // setup the reload semaphore
   sem_init( &reload_sem, 0, 0 );

   reload_thread = md_start_thread( reloader, NULL, true );
   
   // start HTTP
   rc = http_init( &http, &conf, users );
   if( rc != 0 ) {
      exit(1);
   }

   // start validator
   rc = validator_init( &conf );
   if( rc != 0 ) {
      exit(1);
   }

   setup_signals();

   while( 1 ) {
      sleep(1);
   }

   // we never reach this point--the signal handler cleans up
   return 0;
}
Exemplo n.º 6
0
Arquivo: rsa.c Projeto: ahawad/opensgx
/*
 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function
 */
int rsa_rsassa_pss_verify_ext( rsa_context *ctx,
                               int (*f_rng)(void *, unsigned char *, size_t),
                               void *p_rng,
                               int mode,
                               md_type_t md_alg,
                               unsigned int hashlen,
                               const unsigned char *hash,
                               md_type_t mgf1_hash_id,
                               int expected_salt_len,
                               const unsigned char *sig )
{
    int ret;
    size_t siglen;
    unsigned char *p;
    unsigned char buf[POLARSSL_MPI_MAX_SIZE];
    unsigned char result[POLARSSL_MD_MAX_SIZE];
    unsigned char zeros[8];
    unsigned int hlen;
    size_t slen, msb;
    const md_info_t *md_info;
    md_context_t md_ctx;

    if( mode == RSA_PRIVATE && ctx->padding != RSA_PKCS_V21 )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    siglen = ctx->len;

    if( siglen < 16 || siglen > sizeof( buf ) )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    ret = ( mode == RSA_PUBLIC )
          ? rsa_public(  ctx, sig, buf )
          : rsa_private( ctx, f_rng, p_rng, sig, buf );

    if( ret != 0 )
        return( ret );

    p = buf;

    if( buf[siglen - 1] != 0xBC )
        return( POLARSSL_ERR_RSA_INVALID_PADDING );

    if( md_alg != POLARSSL_MD_NONE )
    {
        // Gather length of hash to sign
        //
        md_info = md_info_from_type( md_alg );
        if( md_info == NULL )
            return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

        hashlen = md_get_size( md_info );
    }

    md_info = md_info_from_type( mgf1_hash_id );
    if( md_info == NULL )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    hlen = md_get_size( md_info );
    slen = siglen - hlen - 1; /* Currently length of salt + padding */

    memset( zeros, 0, 8 );

    // Note: EMSA-PSS verification is over the length of N - 1 bits
    //
    msb = mpi_msb( &ctx->N ) - 1;

    // Compensate for boundary condition when applying mask
    //
    if( msb % 8 == 0 )
    {
        p++;
        siglen -= 1;
    }
    if( buf[0] >> ( 8 - siglen * 8 + msb ) )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    md_init( &md_ctx );
    md_init_ctx( &md_ctx, md_info );

    mgf_mask( p, siglen - hlen - 1, p + siglen - hlen - 1, hlen, &md_ctx );

    buf[0] &= 0xFF >> ( siglen * 8 - msb );

    while( p < buf + siglen && *p == 0 )
        p++;

    if( p == buf + siglen ||
        *p++ != 0x01 )
    {
        md_free( &md_ctx );
        return( POLARSSL_ERR_RSA_INVALID_PADDING );
    }

    /* Actual salt len */
    slen -= p - buf;

    if( expected_salt_len != RSA_SALT_LEN_ANY &&
        slen != (size_t) expected_salt_len )
    {
        md_free( &md_ctx );
        return( POLARSSL_ERR_RSA_INVALID_PADDING );
    }

    // Generate H = Hash( M' )
    //
    md_starts( &md_ctx );
    md_update( &md_ctx, zeros, 8 );
    md_update( &md_ctx, hash, hashlen );
    md_update( &md_ctx, p, slen );
    md_finish( &md_ctx, result );

    md_free( &md_ctx );

    if( memcmp( p + slen, result, hlen ) == 0 )
        return( 0 );
    else
        return( POLARSSL_ERR_RSA_VERIFY_FAILED );
}
Exemplo n.º 7
0
int
g_build_math_packet(__g_handle hdl, char *field, char oper, pmda mdm,
    __g_math *ret, uint32_t flags)
{
  g_setjmp(0, "g_build_math_packet", NULL, NULL);
  int rt = 0;
  md_init(mdm, 16);

  __g_math p_math = (__g_math ) mdm->pos->ptr;
  __g_math math = (__g_math ) md_alloc(mdm, sizeof(_g_math));

  if (!math)
    {
      rt = 1;
      goto end;
    }

  math->flags |= flags;

  if ((rt = g_get_math_g_t_ptr(hdl, field, math, 0, p_math)))
    {
      goto end;
    }

  if (!(math->flags & F_MATH_TYPES))
    {
      rt = 6;
      goto end;
    }

  if (math->_m_p)
    {
      math->op_t = m_get_op_proc(oper, math);

      if ( NULL == math->op_t)
        {
          rt = 7;
          goto end;
        }

      /*if (oper == 0x7E)
       {
       math->flags |= F_MATH_IS_SQRT;

       }*/
    }

  if (ret)
    {
      *ret = math;
    }

  end:

  if (rt)
    {
      md_unlink(mdm, mdm->pos);
    }

  return rt;
}
Exemplo n.º 8
0
/*
 * mainline.   crack command line arguments.
 */
int
main(
	int		argc,
	char		*argv[]
)
{
	char		*sname = MD_LOCAL_NAME;
	mdsetname_t	*sp = NULL;
	int		aflag = 0;
	int		pflag = 0;
	int		set_flag = 0;
	mdcmdopts_t	options = (MDCMD_PRINT|MDCMD_DOIT);
	int		c;
	md_error_t	status = mdnullerror;
	md_error_t	*ep = &status;
	int		eval = 1;
	int		error;
	bool_t		called_thru_rpc = FALSE;
	char		*cp;
	int		mnset = FALSE;

	/*
	 * Get the locale set up before calling any other routines
	 * with messages to ouput.  Just in case we're not in a build
	 * environment, make sure that TEXT_DOMAIN gets set to
	 * something.
	 */
#if !defined(TEXT_DOMAIN)
#define	TEXT_DOMAIN "SYS_TEST"
#endif
	(void) setlocale(LC_ALL, "");
	(void) textdomain(TEXT_DOMAIN);

	if ((cp = strstr(argv[0], ".rpc_call")) == NULL) {
		if (sdssc_bind_library() == SDSSC_OKAY)
			if (sdssc_cmd_proxy(argc, argv, SDSSC_PROXY_PRIMARY,
						&error) == SDSSC_PROXY_DONE)
				exit(error);
	} else {
		*cp = '\0'; /* cut off ".rpc_call" */
		called_thru_rpc = TRUE;
	}


	/* initialize */
	if (md_init(argc, argv, 0, 1, ep) != 0 ||
			meta_check_root(ep) != 0)
		goto errout;

	/* parse args */
	optind = 1;
	opterr = 1;
	while ((c = getopt(argc, argv, "hs:afrp?")) != -1) {
		switch (c) {
		case 'h':
			usage(sp, 0);
			break;

		case 's':
			sname = optarg;
			set_flag++;
			break;

		case 'a':
			++aflag;
			options |= MDCMD_FORCE;
			break;

		case 'f':
			options |= MDCMD_FORCE;
			break;

		case 'r':
			options |= MDCMD_RECURSE | MDCMD_FORCE;
			break;
		case 'p':
			++pflag;
			break;
		case '?':
			if (optopt == '?')
				usage(sp, 0);
			/*FALLTHROUGH*/
		default:
			usage(sp, 1);
			break;
		}
	}
	argc -= optind;
	argv += optind;

	/* with mn sets if -a, set name must have been specified by -s */
	if (called_thru_rpc && aflag && !set_flag) {
		md_eprintf(gettext(
		    "-a parameter requires the use of -s in multi-node sets"));
		md_exit(sp, 1);
	}

	/* get set context */
	if ((sp = metasetname(sname, ep)) == NULL) {
		mde_perror(ep, "");
		md_exit(sp, 1);
	}

	if (called_thru_rpc) {
		/* Check if the device is open  on all nodes */
		options |= MDCMD_MN_OPEN_CHECK;
	}

	if (aflag) {	/* clear all devices */
		if (argc != 0)
			usage(sp, 1);

		/*
		 * If a MN set, we will generate a series of individual
		 * metaclear commands which will each grab the set lock.
		 * Therefore do not grab the set lock now.
		 */

		if (!meta_is_mn_set(sp, ep)) {
			/* grab set lock */
			if (meta_lock(sp, TRUE, ep))
				goto errout;

			/* check for ownership */
			if (meta_check_ownership(sp, ep) != 0)
				goto errout;
		} else {
			mnset = TRUE;
		}

		/* reset all devices in set */
		if (meta_reset_all(sp, options, ep) != 0) {
			if (!mnset)
				mde_perror(ep, "");
		} else
			eval = 0;
	} else {
		/*
		 * We are dealing with either a single or multiple names.
		 * The set for the command is either denoted by the -s option
		 * or the set of the first name.
		 */
		if (argc <= 0)
			usage(sp, 1);

		if (meta_is_mn_name(&sp, argv[0], ep))
			mnset = TRUE;
		eval = 0;

		for (; (argc > 0); --argc, ++argv) {
			char		*cname;

			/*
			 * If we are dealing with a MN set and we were not
			 * called thru an rpc call, we are just to send this
			 * command string to the master of the set and let it
			 * deal with it.
			 */
			if (!called_thru_rpc && mnset) {
				/* get the canonical name */
				if (pflag) {
					/*
					 * If -p, set cname to the device
					 * argument.
					 */
					cname = Strdup(argv[0]);
				} else {
					/*
					 * For hotspares and metadevices, set
					 * cname to the full name,
					 * setname/hspxxx or setname/dxxx
					 */
					cname = meta_name_getname(&sp,
					    argv[0], META_DEVICE, ep);
					if (cname == NULL) {
						mde_perror(ep, "");
						eval = 1;
						continue;
					}
				}
				if (meta_mn_send_metaclear_command(sp,
				    cname, options, pflag, ep) != 0) {
					eval = 1;
				}
				Free(cname);
			} else {
				if (pflag) {
					/*
					 * clear all soft partitions on named
					 * devices
					 */
					if (meta_sp_reset_component(sp, argv[0],
					    options, ep) != 0) {
						mde_perror(ep, "");
						eval = 1;
						continue;
					}
				} else {
					/*
					 * get the canonical name and
					 * setup sp if it has been
					 * specified as part of the
					 * metadevice/hsp name param
					 */
					cname = meta_name_getname(&sp,
					    argv[0], META_DEVICE, ep);
					if (cname == NULL) {
						mde_perror(ep, "");
						eval = 1;
						continue;
					}

					/* clear named devices */
					if (clear_name(&sp, cname,
					    options, ep) != 0) {
						mde_perror(ep, "");
						eval = 1;
						Free(cname);
						continue;
					}
					Free(cname);
				}
			}
		}
	}
	/* update md.cf */
	if (meta_update_md_cf(sp, ep) != 0) {
		mde_perror(ep, "");
		eval = 1;
	}
	md_exit(sp, eval);

errout:
	mde_perror(ep, "");
	md_exit(sp, eval);
	/*NOTREACHED*/
	return (eval);
}
Exemplo n.º 9
0
Arquivo: rsa.c Projeto: ahawad/opensgx
/*
 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function
 */
int rsa_rsassa_pss_sign( rsa_context *ctx,
                         int (*f_rng)(void *, unsigned char *, size_t),
                         void *p_rng,
                         int mode,
                         md_type_t md_alg,
                         unsigned int hashlen,
                         const unsigned char *hash,
                         unsigned char *sig )
{
    size_t olen;
    unsigned char *p = sig;
    unsigned char salt[POLARSSL_MD_MAX_SIZE];
    unsigned int slen, hlen, offset = 0;
    int ret;
    size_t msb;
    const md_info_t *md_info;
    md_context_t md_ctx;

    if( mode == RSA_PRIVATE && ctx->padding != RSA_PKCS_V21 )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    if( f_rng == NULL )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    olen = ctx->len;

    if( md_alg != POLARSSL_MD_NONE )
    {
        // Gather length of hash to sign
        //
        md_info = md_info_from_type( md_alg );
        if( md_info == NULL )
            return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

        hashlen = md_get_size( md_info );
    }

    md_info = md_info_from_type( ctx->hash_id );
    if( md_info == NULL )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    hlen = md_get_size( md_info );
    slen = hlen;

    if( olen < hlen + slen + 2 )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    memset( sig, 0, olen );

    // Generate salt of length slen
    //
    if( ( ret = f_rng( p_rng, salt, slen ) ) != 0 )
        return( POLARSSL_ERR_RSA_RNG_FAILED + ret );

    // Note: EMSA-PSS encoding is over the length of N - 1 bits
    //
    msb = mpi_msb( &ctx->N ) - 1;
    p += olen - hlen * 2 - 2;
    *p++ = 0x01;
    memcpy( p, salt, slen );
    p += slen;

    md_init( &md_ctx );
    md_init_ctx( &md_ctx, md_info );

    // Generate H = Hash( M' )
    //
    md_starts( &md_ctx );
    md_update( &md_ctx, p, 8 );
    md_update( &md_ctx, hash, hashlen );
    md_update( &md_ctx, salt, slen );
    md_finish( &md_ctx, p );

    // Compensate for boundary condition when applying mask
    //
    if( msb % 8 == 0 )
        offset = 1;

    // maskedDB: Apply dbMask to DB
    //
    mgf_mask( sig + offset, olen - hlen - 1 - offset, p, hlen, &md_ctx );

    md_free( &md_ctx );

    msb = mpi_msb( &ctx->N ) - 1;
    sig[0] &= 0xFF >> ( olen * 8 - msb );

    p += hlen;
    *p++ = 0xBC;

    return( ( mode == RSA_PUBLIC )
            ? rsa_public(  ctx, sig, sig )
            : rsa_private( ctx, f_rng, p_rng, sig, sig ) );
}
Exemplo n.º 10
0
int
g_process_math_string(__g_handle hdl, char *string, pmda mdm, pmda chain,
    int *ret, void **p_ret, uint32_t flags, uint32_t int_flags)
{
  g_setjmp(0, "g_process_math_string", NULL, NULL);
  char *ptr = string, *left, oper = 0x0;
  size_t i;

  size_t sin_len = strlen(string);

  if (sin_len == 0)
    {
      return 0;
    }

  //g_del_char(string, string_p, 0x20);

  int f_ret = 0;

  while (ptr[0])
    {
      if (ptr[0] == 0x0 || ptr[0] == 0x23 || ptr[0] == 0x7D || ptr[0] == 0x29
          || ptr[0] == 0x3A)
        {
          if (ptr[0] == 0x29)
            {
              if (!(int_flags & F_PROC_MATH_STR_INB))
                {
                  f_ret = 0;
                  goto f_end;
                }
              else
                {
                  *p_ret = ptr;
                }
            }
          else
            {
              /*if ((int_flags & F_PROC_MATH_STR_INB))
               {
               return 12;
               }*/
            }
          break;
        }

      while (ptr[0] == 0x20)
        {
          ptr++;
        }

      if (ptr[0] == 0x28)
        {
          if (ptr[1] == 0x29)
            {
              break;
            }
          pmda object = (pmda) md_alloc(chain, sizeof(mda));

          if (NULL == object)
            {
              f_ret = -1;
              goto f_end;
            }

          md_init(object, 8);
          char *pms_ret = "";

          ptr++;

          int r = g_process_math_string(hdl, ptr, object, chain, ret,
              (void*) &pms_ret, flags, int_flags | F_PROC_MATH_STR_INB);
          if (0 != r)
            {
              ERROR(
                  "g_process_math_string (F_PROC_MATH_STR_INB): FAILED: [%d]: %s\n",
                  r, pms_ret);
              md_free(object);
              f_ret = r;
              goto f_end;
            }
          else
            {
              __g_math math_c = (__g_math ) m_find_last_dtype(chain,
                  chain->pos);
              __g_math math = (__g_math ) md_alloc(mdm, sizeof(_g_math));

              if (NULL == math)
                {
                  f_ret = 16;
                  goto f_end;
                }

              if (NULL == math_c)
                {
                  f_ret = 17;
                  goto f_end;
                }

              math->next = object;
              math->flags |= F_MATH_NITEM;

              pms_ret++;
              ptr = pms_ret;

              math->flags |= (math_c->flags & F_MATH_TYPES);

              __g_math math_p = (__g_math ) m_find_prev_dtype(mdm,
                  (p_md_obj) mdm->pos);

              math->_m_p = g_get_math_m_p(math, math_p);

              if (!(is_ascii_arith_bin_oper(ptr[0])))
                {
                  if (NULL == math_c->_m_p)
                    {
                      f_ret = 21;
                      goto f_end;
                    }

                  math->op_t = m_get_op_proc(ptr[0], math_c);

                  if ( NULL == math->op_t)
                    {
                      f_ret = 22;
                      goto f_end;
                    }

                  //math->_m_p = math_c->_m_p;
                }

              math->vb = math_c->vb;
              math->l_off = math_c->l_off;

              if (ptr[0] == 0x0 || ptr[0] == 0x23 || ptr[0] == 0x7D
                  || ptr[0] == 0x3A || ptr[0] == 0x29)
                {
                  continue;
                }

              ptr++;

              continue;
            }

        }

      i = 0;

      left = ptr;

      uint32_t add_flags = 0;

      char in_dummy[8192];

      if (ptr[0] == 0x5B)
        {
          void *l_next_ref;

          char *s_ptr = l_mppd_shell_ex(ptr, in_dummy, sizeof(in_dummy),
              &l_next_ref,
              0x5B,
              0x5D, F_MPPD_SHX_TZERO);

          if (NULL == s_ptr)
            {
              f_ret = 130;
              goto f_end;
            }

          if (NULL == l_next_ref || ((char*) l_next_ref)[0] == 0x0)
            {
              f_ret = 131;
              goto f_end;
            }

          left = s_ptr;
          ptr = l_next_ref;
          add_flags |= F_MATH_STRCONV;
        }
      else
        {

          if (ptr[0] == 0x2B || ptr[0] == 0x2D)
            {
              ptr++;
            }

          while (is_ascii_arith_bin_oper(ptr[0]) && ptr[0] && ptr[0] != 0x23
              && ptr[0] != 0x7D && ptr[0] != 0x29 && ptr[0] != 0x3A
              && ptr[0] != 0x29 && ptr[0] != 0x20)
            {
              i++;
              ptr++;
            }

          if (!i)
            {
              f_ret = 1;
              goto f_end;
            }
        }

      if (ptr[0] && ptr[0] != 0x23 && ptr[0] != 0x7D && ptr[0] != 0x29
          && ptr[0] != 0x3A && ptr[0] != 0x29)
        {
          if (is_ascii_arith_bin_oper(ptr[0]))
            {
              f_ret = 23;
              goto f_end;
            }

          if (ptr[0] == 0x3C || ptr[0] == 0x3E)
            {
              if (ptr[0] != ptr[1])
                {
                  f_ret = 2;
                  goto f_end;
                }
              ptr++;
            }
          oper = ptr[0];
          ptr++;
        }
      else
        {
          oper = 0x0;
        }

      __g_math mm;
      *ret = g_build_math_packet(hdl, left, oper, mdm, &mm, flags | add_flags);

      if (*ret)
        {
          f_ret = 6;
          goto f_end;
        }

      if (oper == 0x7E && (ptr[0] == 0x7D || ptr[0] == 0x29))
        {
          *ret = g_build_math_packet(hdl, left, oper, mdm, NULL,
              flags | add_flags);
          if (*ret)
            {
              f_ret = 7;
              goto f_end;
            }
        }

    }

  f_end: ;

  //free(string_p);

  return f_ret;
}
Exemplo n.º 11
0
Arquivo: rsa.c Projeto: ahawad/opensgx
/*
 * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
 */
int rsa_rsaes_oaep_encrypt( rsa_context *ctx,
                            int (*f_rng)(void *, unsigned char *, size_t),
                            void *p_rng,
                            int mode,
                            const unsigned char *label, size_t label_len,
                            size_t ilen,
                            const unsigned char *input,
                            unsigned char *output )
{
    size_t olen;
    int ret;
    unsigned char *p = output;
    unsigned int hlen;
    const md_info_t *md_info;
    md_context_t md_ctx;

    if( mode == RSA_PRIVATE && ctx->padding != RSA_PKCS_V21 )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    if( f_rng == NULL )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    md_info = md_info_from_type( ctx->hash_id );
    if( md_info == NULL )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    olen = ctx->len;
    hlen = md_get_size( md_info );

    if( olen < ilen + 2 * hlen + 2 )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    memset( output, 0, olen );

    *p++ = 0;

    // Generate a random octet string seed
    //
    if( ( ret = f_rng( p_rng, p, hlen ) ) != 0 )
        return( POLARSSL_ERR_RSA_RNG_FAILED + ret );

    p += hlen;

    // Construct DB
    //
    md( md_info, label, label_len, p );
    p += hlen;
    p += olen - 2 * hlen - 2 - ilen;
    *p++ = 1;
    memcpy( p, input, ilen );

    md_init( &md_ctx );
    md_init_ctx( &md_ctx, md_info );

    // maskedDB: Apply dbMask to DB
    //
    mgf_mask( output + hlen + 1, olen - hlen - 1, output + 1, hlen,
               &md_ctx );

    // maskedSeed: Apply seedMask to seed
    //
    mgf_mask( output + 1, hlen, output + hlen + 1, olen - hlen - 1,
               &md_ctx );

    md_free( &md_ctx );

    return( ( mode == RSA_PUBLIC )
            ? rsa_public(  ctx, output, output )
            : rsa_private( ctx, f_rng, p_rng, output, output ) );
}
Exemplo n.º 12
0
Arquivo: rsa.c Projeto: ahawad/opensgx
/*
 * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
 */
int rsa_rsaes_oaep_decrypt( rsa_context *ctx,
                            int (*f_rng)(void *, unsigned char *, size_t),
                            void *p_rng,
                            int mode,
                            const unsigned char *label, size_t label_len,
                            size_t *olen,
                            const unsigned char *input,
                            unsigned char *output,
                            size_t output_max_len )
{
    int ret;
    size_t ilen, i, pad_len;
    unsigned char *p, bad, pad_done;
    unsigned char buf[POLARSSL_MPI_MAX_SIZE];
    unsigned char lhash[POLARSSL_MD_MAX_SIZE];
    unsigned int hlen;
    const md_info_t *md_info;
    md_context_t md_ctx;

    /*
     * Parameters sanity checks
     */
    if( mode == RSA_PRIVATE && ctx->padding != RSA_PKCS_V21 )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    ilen = ctx->len;

    if( ilen < 16 || ilen > sizeof( buf ) )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    md_info = md_info_from_type( ctx->hash_id );
    if( md_info == NULL )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    /*
     * RSA operation
     */
    ret = ( mode == RSA_PUBLIC )
          ? rsa_public(  ctx, input, buf )
          : rsa_private( ctx, f_rng, p_rng, input, buf );

    if( ret != 0 )
        return( ret );

    /*
     * Unmask data and generate lHash
     */
    hlen = md_get_size( md_info );

    md_init( &md_ctx );
    md_init_ctx( &md_ctx, md_info );

    /* Generate lHash */
    md( md_info, label, label_len, lhash );

    /* seed: Apply seedMask to maskedSeed */
    mgf_mask( buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,
               &md_ctx );

    /* DB: Apply dbMask to maskedDB */
    mgf_mask( buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,
               &md_ctx );

    md_free( &md_ctx );

    /*
     * Check contents, in "constant-time"
     */
    p = buf;
    bad = 0;

    bad |= *p++; /* First byte must be 0 */

    p += hlen; /* Skip seed */

    /* Check lHash */
    for( i = 0; i < hlen; i++ )
        bad |= lhash[i] ^ *p++;

    /* Get zero-padding len, but always read till end of buffer
     * (minus one, for the 01 byte) */
    pad_len = 0;
    pad_done = 0;
    for( i = 0; i < ilen - 2 * hlen - 2; i++ )
    {
        pad_done |= p[i];
        pad_len += ( pad_done == 0 );
    }

    p += pad_len;
    bad |= *p++ ^ 0x01;

    /*
     * The only information "leaked" is whether the padding was correct or not
     * (eg, no data is copied if it was not correct). This meets the
     * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between
     * the different error conditions.
     */
    if( bad != 0 )
        return( POLARSSL_ERR_RSA_INVALID_PADDING );

    if( ilen - ( p - buf ) > output_max_len )
        return( POLARSSL_ERR_RSA_OUTPUT_TOO_LARGE );

    *olen = ilen - (p - buf);
    memcpy( output, p, *olen );

    return( 0 );
}
Exemplo n.º 13
0
static void
lib_md_reset(mrb_state *mrb, struct mrb_md *md)
{
  md_init(md->type, md->ctx);
}
Exemplo n.º 14
0
int
parse_args(int argc, char **argv, _gg_opt fref_t[], char ***la, uint32_t flags)
{
  g_setjmp(0, "parse_args", NULL, NULL);
  int vi, ret, c = 0;

  if (ar_vref.count)
    {
      md_free(&ar_vref);
    }

  md_init(&ar_vref, 8);

  int i;

  char *c_arg = NULL;
  char **c_argv = NULL;

  __gg_opt ora = (__gg_opt) fref_t;

  _g_vop vop =
    { 0 };

  errno = 0;

  for (i = 1, ret = 0, vi = -1; i < argc; i++, vi = -1)
    {
      c_arg = argv[i];
      c_argv = &argv[i];

      char *p_iseq = strchr(c_arg, 0x3D);

      if (p_iseq)
        {
          char bp_opt[64];
          size_t p_isl = p_iseq - c_arg;
          p_isl > 63 ? p_isl = 63 : 0;
          strncpy(bp_opt, c_arg, p_isl);
          bp_opt[p_isl] = 0x0;
          p_iseq++;

          ret = process_opt_n(bp_opt, p_iseq, fref_t, 2, &vi, (void*) &vop);
        }
      else
        {
          ret = process_opt_n(c_arg, (char*) &argv[i + 1], fref_t, 0, &vi,
              (void*) &vop);
        }

      ar_check_ttl_expired(&ar_vref);
      ar_mod_ttl(&ar_vref, -1);

      if (ret == -2)
        {
          if (flags & F_PARSE_ARG_IGNORE_NOT_FOUND)
            {
              continue;
            }
        }
      if (0 != ret)
        {
          if (!(flags & F_PARSE_ARG_SILENT))
            {
              if (ret == -2)
                {
                  fprintf(stderr, "ERROR: [%d] invalid option '%s'\n", ret,
                      c_arg);
                }
              else if (ret == -4)
                {
                  fprintf(stderr,
                      "ERROR: [%d] CRITICAL: improperly configured option ref table\n",
                      ret);
                  abort();
                }
              else if (ret > 0)
                {
                  fprintf(stderr, "ERROR: [%d] '%s': bad option argument\n",
                      ret, c_arg);
                }

            }
          if (!(flags & F_PARSE_ARG_IGNORE_ERRORS))
            {
              c = -2;
              break;
            }
        }
      else
        {
          c++;
        }

      if (NULL == p_iseq && vi > -1)
        {
          uint8_t ac = ora[vi].ac;
          if (0 != vop.ac_s)
            {
              ac += vop.ac_s;
              vop.ac_s = 0;
            }
          i += (int) ac;
        }
    }

  if (!(flags & F_PARSE_ARG_IGNORE_ERRORS) && !c)
    {
      return -1;
    }

  if ( NULL != la)
    {
      *la = (char**) c_argv;
    }

  return ret;
}
Exemplo n.º 15
0
/*
 * main:
 *	The main program, of course
 */
int
main(int argc, char **argv)
{
    char *env;
    time_t lowtime;

    md_init();

#ifdef MASTER
    /*
     * Check to see if he is a wizard
     */
    if (argc >= 2 && argv[1][0] == '\0')
	if (strcmp(PASSWD, md_crypt(md_getpass("wizard's password: "******"mT")) == 0)
	{
	    wizard = TRUE;
	    player.t_flags |= SEEMONST;
	    argv++;
	    argc--;
	}

#endif

    /*
     * get home and options from environment
     */

    strcpy(home, md_gethomedir());

	if (strlen(home) > MAXSTR - strlen("rogue.save") - 1)
		*home = 0;

    strcpy(file_name, home);
    strcat(file_name, "rogue.save");

    if ((env = getenv("ROGUEOPTS")) != NULL)
	parse_opts(env);
    if (env == NULL || whoami[0] == '\0')
        strucpy(whoami, md_getusername(), strlen(md_getusername()));
    lowtime = time(NULL);
    if (getenv("SEED") != NULL)
    {
	dnum = atoi(getenv("SEED"));
	noscore = 1;
    }
    else
	dnum = (unsigned int) lowtime + md_getpid();
    seed = dnum;

    open_score();

	/* 
     * Drop setuid/setgid after opening the scoreboard file. 
     */ 

    md_normaluser();

    /*
     * check for print-score option
     */

	md_normaluser(); /* we drop any setgid/setuid priveldges here */

    if (argc == 2)
    {
	if (strcmp(argv[1], "-s") == 0)
	{
	    noscore = TRUE;
	    score(0, -1, 0);
	    exit(0);
	}
	else if (strcmp(argv[1], "-d") == 0)
	{
	    dnum = rnd(100);	/* throw away some rnd()s to break patterns */
	    while (--dnum)
		rnd(100);
	    purse = rnd(100) + 1;
	    level = rnd(100) + 1;
	    initscr();
	    getltchars();
	    death(death_monst());
	    exit(0);
	}
    }

    init_check();			/* check for legal startup */
    if (argc == 2)
	if (!restore(argv[1]))	/* Note: restore will never return */
	    my_exit(1);
#ifdef MASTER
    if (wizard)
	printf("Hello %s, welcome to dungeon #%d", whoami, dnum);
    else
#endif
	printf("Hello %s, just a moment while I dig the dungeon...", whoami);
    fflush(stdout);

    initscr();				/* Start up cursor package */
    init_probs();			/* Set up prob tables for objects */
    init_player();			/* Set up initial player stats */
    init_names();			/* Set up names of scrolls */
    init_colors();			/* Set up colors of potions */
    init_stones();			/* Set up stone settings of rings */
    init_materials();			/* Set up materials of wands */
    setup();

    /*
     * The screen must be at least NUMLINES x NUMCOLS
     */
    if (LINES < NUMLINES || COLS < NUMCOLS)
    {
	printf("\nSorry, the screen must be at least %dx%d\n", NUMLINES, NUMCOLS);
	endwin();
	my_exit(1);
    }

    /*
     * Set up windows
     */
    hw = newwin(LINES, COLS, 0, 0);
    idlok(stdscr, TRUE);
    idlok(hw, TRUE);
#ifdef MASTER
    noscore = wizard;
#endif
    new_level();			/* Draw current level */
    /*
     * Start up daemons and fuses
     */
    start_daemon(runners, 0, AFTER);
    start_daemon(doctor, 0, AFTER);
    fuse(swander, 0, WANDERTIME, AFTER);
    start_daemon(stomach, 0, AFTER);
    playit();
    return(0);
}
Exemplo n.º 16
0
int
main(int argc, char **argv)
{
	char		c;
	char		*sname = MD_LOCAL_NAME;
	mddevopts_t	options = 0;
	md_error_t	status = mdnullerror;
	md_error_t	*ep = &status;
	mdsetname_t	*sp = NULL;
	mdsetname_t	*local_sp = NULL;
	char		*argname;
	int		todo = 0;
	int		ret = 0;
	int		md_upgd_stat = 0;
	int		error;
	md_set_desc	*sd;

	/*
	 * Get the locale set up before calling any other routines
	 * with messages to ouput.  Just in case we're not in a build
	 * environment, make sure that TEXT_DOMAIN gets set to
	 * something.
	 */
#if !defined(TEXT_DOMAIN)
#define	TEXT_DOMAIN "SYS_TEST"
#endif
	(void) setlocale(LC_ALL, "");
	(void) textdomain(TEXT_DOMAIN);

	if ((sdssc_bind_library() == SDSSC_OKAY) &&
	    (sdssc_cmd_proxy(argc, argv, SDSSC_PROXY_PRIMARY,
	    &error) == SDSSC_PROXY_DONE))
		exit(error);

	openlog("metadevadm", LOG_ODELAY, LOG_USER);

	/* initialize */
	if (md_init(argc, argv, 0, 1, ep) != 0 ||
	    meta_check_root(ep) != 0) {
		closelog();
		mde_perror(ep, "");
		md_exit(sp, 1);
	}

	/* parse args */
	optind = 1;
	opterr = 1;
	while ((c = getopt(argc, argv, "vlhnrs:u:")) != -1) {
		switch (c) {
		case 'v':
			options |= DEV_VERBOSE;
			break;
		case 'n':
			options |= DEV_NOACTION;
			break;
		case 'r':
			options |= DEV_RELOAD;
			todo = 1;
			break;
		case 's':
			sname = optarg;
			break;
		case 'u':
			todo = 1;
			options |= DEV_UPDATE;
			argname = optarg;
			if (argname == NULL) {
				usage("metadevadm");
				closelog();
				md_exit(sp, 0);
			}
			break;
		case 'l':
			options |= DEV_LOG;
			break;
		case 'h':
		default:
			usage("metadevadm");
			closelog();
			md_exit(sp, 0);
		}
	}

	if ((sp = metasetname(sname, ep)) == NULL) {
		mde_perror(ep, "");
		closelog();
		md_exit(sp, 1);
	}

	if (!metaislocalset(sp)) {
		if ((sd = metaget_setdesc(sp, ep)) == NULL) {
			mde_perror(ep, "");
			closelog();
			md_exit(sp, 1);
		}
		if (MD_MNSET_DESC(sd)) {
			(void) printf("%s\n", gettext("metadevadm cannot be "
			    "run on multi-owner disksets\n"));
			closelog();
			md_exit(sp, 0);
		}
	}

	if ((options & DEV_VERBOSE) && (todo != 1)) {
		usage("metadevadm");
		closelog();
		md_exit(sp, 0);
	}

	if ((options & DEV_NOACTION) && (todo != 1)) {
		usage("metadevadm");
		closelog();
		md_exit(sp, 0);
	}

	if (todo == 0) {
		usage("metadevadm");
		closelog();
		md_exit(sp, 0);
	}

	if ((local_sp = metasetname(MD_LOCAL_NAME, ep)) == NULL) {
		mde_perror(ep, "");
		closelog();
		md_exit(local_sp, 1);
	}

	/* lock the local set */
	if (meta_lock(local_sp, TRUE, ep) != 0) {
		mde_perror(ep, "");
		closelog();
		md_exit(local_sp, 1);
	}

	/* grab set lock */
	if (meta_lock(sp, TRUE, ep)) {
		mde_perror(ep, "");
		closelog();
		md_exit(local_sp, 1);
	}

	/* check for ownership */
	if (meta_check_ownership(sp, ep) != 0) {
		/*
		 * If the set is not owned by this node then only update the
		 * local set's replica.
		 */
		options |= DEV_LOCAL_SET;
	}

	/*
	 * check for upgrade. If upgrade in progress then just exit.
	 */
	if (metaioctl(MD_UPGRADE_STAT, &md_upgd_stat, ep, NULL) != 0) {
			mde_perror(ep, "");
			closelog();
			(void) meta_unlock(sp, ep);
			md_exit(local_sp, 1);
	}
	if (md_upgd_stat == 0) {
		ret = meta_fixdevid(sp, options, argname, ep);
		if (ret == METADEVADM_ERR) {
			/*
			 * If the call failed, for a DEV_RELOAD still need to
			 * update the .conf file to provide the latest devid
			 * information so exit later.
			 */
			if (options & DEV_UPDATE) {
				closelog();
				(void) meta_unlock(sp, ep);
				md_exit(local_sp, 1);
			}
		}
	}

	/*
	 * Sync replica list in kernel to replica list in conf files.
	 * This will update driver name and minor number in conf file
	 * if reload was run.  Will update device id in conf file if
	 * update was run.
	 */
	meta_sync_db_locations(sp, ep);
	closelog();
	(void) meta_unlock(sp, ep);
	md_exit(local_sp, ret);
	return (0);
}
Exemplo n.º 17
0
int main( int argc, char *argv[] )
{
    int ret, i;
    const md_info_t *md_info;
    md_context_t md_ctx;

    md_init( &md_ctx );

    if( argc == 1 )
    {
        const int *list;

        printf( "print mode:  generic_sum <md> <file> <file> ...\n" );
        printf( "check mode:  generic_sum <md> -c <checksum file>\n" );

        printf( "\nAvailable message digests:\n" );
        list = md_list();
        while( *list )
        {
            md_info = md_info_from_type( *list );
            printf( "  %s\n", md_info->name );
            list++;
        }

#if defined(_WIN32)
        printf( "\n  Press Enter to exit this program.\n" );
        fflush( stdout ); getchar();
#endif

        return( 1 );
    }

    /*
     * Read the MD from the command line
     */
    md_info = md_info_from_string( argv[1] );
    if( md_info == NULL )
    {
        fprintf( stderr, "Message Digest '%s' not found\n", argv[1] );
        return( 1 );
    }
    if( md_init_ctx( &md_ctx, md_info) )
    {
        fprintf( stderr, "Failed to initialize context.\n" );
        return( 1 );
    }

    ret = 0;
    if( argc == 4 && strcmp( "-c", argv[2] ) == 0 )
    {
        ret |= generic_check( md_info, argv[3] );
        goto exit;
    }

    for( i = 2; i < argc; i++ )
        ret |= generic_print( md_info, argv[i] );

exit:
    md_free( &md_ctx );

    return( ret );
}