Beispiel #1
0
int
decode_vrrp(u_char *buf, int len, u_char *obuf, int olen)
{
	struct buf *b, inbuf, outbuf;
	struct vrrp_header *vrrp;

	buf_init(&inbuf, buf, len);
	buf_init(&outbuf, obuf, olen);
	
	vrrp = (struct vrrp_header *)buf_ptr(&inbuf);
	
	if (buf_len(&inbuf) < sizeof(*vrrp))
		return (0);
	
	/* We only care about VRRP_AUTH_SIMPLE */
	if (ntohs(vrrp->vr_auth) != VRRP_AUTH_SIMPLE)
		return (0);
	
	/* XXX - probably want to verify checksum */
	
	/* Forward to Authentication Data */
	buf_skip(&inbuf, sizeof(*vrrp) + 8 + (vrrp->vr_naddr * 4));

	if ((b = buf_tok(&inbuf, NULL, VRRP_AUTH_DATA_LEN)) == NULL)
		return (0);
	
	buf_put(&outbuf, buf_ptr(b), buf_len(b));
	buf_put(&outbuf, "\n", 1);
	buf_end(&outbuf);
	
	return (buf_len(&outbuf));
}
Beispiel #2
0
int use_blk(ALLOC * a, handle_t h, void *buf, size_t len)
{
	size_t need = len_need(len);
	size_t padding = len2atom(len) * ATOM_LEN - need;
	unsigned char *b;

	if ((b = buf_get(a, need + padding)) == NULL)
		return -1;

	if (len <= CTBLK_MAXSHORT) {
		b[0] = CTBLK_SHORT;
		b[1] = (unsigned char)len;
		memcpy(&b[2], buf, len);
		bzero(&b[2 + len], padding);
	} else {
		b[0] = CTBLK_LONG;
		uint16tob(&b[1], len);
		memcpy(&b[3], buf, len);
		bzero(&b[3 + len], padding);
	}
	if (writeat(a->fd, b, need + padding, hdl2off(h)) != need + padding) {
		buf_put(a, b);
		return -1;
	}
	buf_put(a, b);
	return 0;
}
Beispiel #3
0
void
case_buf_put()
{
    struct buf *buf = buf(NULL);
    assert(buf_put(buf, "abc", 3) == BUF_OK);
    assert(strcmp(str(buf), "abc") == 0);
    assert(buf_put(buf, "efg", 3) == BUF_OK);
    assert(strcmp(str(buf), "abcefg") == 0);
    buf_free(buf);
}
Beispiel #4
0
int
isns_authblock_encode(buf_t *bp, const struct isns_authblk *auth)
{
	if (!buf_put32(bp, auth->iab_bsd)
	 || !buf_put32(bp, auth->iab_length)
	 || !buf_put64(bp, auth->iab_timestamp)
	 || !buf_put32(bp, auth->iab_spi_len)
	 || !buf_put(bp, auth->iab_spi, auth->iab_spi_len)
	 || !buf_put(bp, auth->iab_sig, auth->iab_sig_len))
		return 0;
	return 1;
}
Beispiel #5
0
Datei: ht.c Projekt: taysom/tau
STATIC void node_dump(Linear_s *t, Blknum_t blknum, int indent)
{
	Buf_s	*buf;
	Node_s	*node;
	Blknum_t overflow;

	if (!blknum) return;
	buf = t_get(t, blknum);
	node = buf->d;
	Hrec_s	rec;
	unint	i;

	if (Dump_buf) {
		pr_buf(buf, indent);
	}
	pr_head(node, indent);
	for (i = 0; i < node->numrecs; i++) {
		rec = get_rec(node, i);
		pr_indent(indent);
		printf("%ld. ", i);
		rec_dump(rec);
	}
	overflow = node->overflow;
	buf_put(&buf);
	if (overflow) {
		node_dump(t, overflow, indent+1);
	}
}
Beispiel #6
0
handle_t alloc_record(ALLOC * a, table_t * t, record_t * r)
{
    unsigned char *buf, *p;
    handle_t h = 0;

    if (_validate_record(a, t, r) < 0 || _validate_unique(a, t, r) < 0)
        return 0;
    if ((buf = buf_get(a, _sizeof_record(t, r))) == NULL)
        return 0;

    r->prev = t->tail;
    r->next = 0;
    p = record2b(buf, t, r);
    h = alloc_blk(a, buf, p - buf);
    buf_put(a, buf);
    if (h == 0)
        return 0;
    r->self = h;
    if (_list_add_record(a, t, r) < 0)
        return 0;

    for (int i = 0; i < t->ncols; i++)
        if (t->cols[i].index != 0)
            index_set(t->cols[i].idx, r, i);

    return h;
}
int aesctr_packet_get(struct buf *b) {

    long long len;
    struct buf *recvbuf = &packet.recvbuf;
    unsigned char *pp;
    long long l;

    /* we need at least one block */
    if (recvbuf->len - ZB < BB) { packet.packet_length = 0; return 1; }

    /* decrypt first block  */
    if (packet.packet_length == 0) {
        if (sshcrypto_stream_xor(
            recvbuf->buf + ZB,                  /* c    */
            recvbuf->buf + ZB,                  /* m    */
            BB,                                 /* mlen */
            packet.clientnonce,                 /* n    */
            packet.clientkey                    /* k    */
        ) != 0) bug_proto();
        packet.packet_length = uint32_unpack_big(recvbuf->buf + ZB);
    }

    if (packet.packet_length > PACKET_LIMIT) bug_proto();
    if (packet.packet_length + 4 + AB > recvbuf->len - ZB) return 1;


    /* decrypt and check MAC */
    uint32_pack_big(recvbuf->buf + ZB - 4, packet.receivepacketid++);
    if (sshcrypto_stream_xor(
            recvbuf->buf + ZB + BB,             /* c    */
            recvbuf->buf + ZB + BB,             /* m    */
            packet.packet_length + 4 - BB,      /* mlen */
            packet.clientnonce,                 /* n    */
            packet.clientkey                    /* k    */
        ) != 0) bug_proto();

    if (sshcrypto_auth(
            recvbuf->buf,                       /* a    */
            recvbuf->buf + ZB - 4,              /* m    */
            packet.packet_length + 8,           /* mlen */
            packet.clientmackey                 /* k    */
        ) != 0) bug_proto();

    if (crypto_verify_32(recvbuf->buf, recvbuf->buf + ZB + packet.packet_length + 4) != 0) bug_proto();

    len = packet.packet_length;
    len -= recvbuf->buf[ZB + 4] + 1;
    if (len <= 0) bug_proto();
    buf_put(b, recvbuf->buf + ZB + 5, len);

    pp = recvbuf->buf + ZB;
    l  = recvbuf->len - ZB;

    byte_copy(pp, l - packet.packet_length + AB + 4, pp + packet.packet_length + AB + 4);
    purge(pp + l - packet.packet_length + AB + 4, packet.packet_length + AB + 4);
    recvbuf->len -= packet.packet_length + AB + 4;
    packet.packet_length = 0;
    purge(recvbuf->buf, ZB);
    return 1;
}
Beispiel #8
0
int main(int argc, char **argv)
{
  int pth1;  

  pthread_t thread_serv_listen;
  pthread_attr_t attr; // set of attributes for the thread 
  pthread_attr_init(&attr); // get the default attributes 

  s = setup_listen(SERVER_PORT);
  if (s < 0) {
    printf("error opening server\n");
    exit(1);
  }else{
    printf("server started\n");
  }

  if( (pth1 = pthread_create( &thread_serv_listen, &attr, server_listen, NULL)) ){
    printf("Server listen thread creation failed: %d\n", pth1);
  }else{
    printf("Server thread created\n");
  }


  while(1){
//    printf("while1 read temp\n");
    usleep(1000000); // cakamo eno sekundo
    buf_put((element_t)get_temp());
  }
  close(s);

  return 0;
}
Beispiel #9
0
int
decode_citrix(u_char *buf, int len, u_char *obuf, int olen)
{
	struct buf inbuf, outbuf;
	u_char key, c, t[2];
	int i;
	
	buf_init(&inbuf, buf, len);
	buf_init(&outbuf, obuf, olen);
	
	while ((i = buf_index(&inbuf, ica_magic, sizeof(ica_magic))) >= 0) {
		buf_skip(&inbuf, i);
		
		if (buf_len(&inbuf) < 60)
			break;
		
		buf_skip(&inbuf, 17);
		
		if (buf_get(&inbuf, &key, 1) != 1)
			break;
		
		buf_skip(&inbuf, 42);
		
		if (buf_get(&inbuf, &c, 1) != 1)
			break;

		c ^= ('C' | key);
		
		buf_put(&outbuf, &c, 1);
		
		i = 0;
		while (buf_get(&inbuf, t, 2) == 2) {
			c = t[0] ^ t[1] ^ key;
			
			if (c == '\0') {
				buf_put(&outbuf, "\n", 1);
				if (++i > 2) break;
			}
			buf_put(&outbuf, &c, 1);
		}
	}
	buf_end(&outbuf);
	
	return (buf_len(&outbuf));
}
Beispiel #10
0
char* 
yarr_toString(UnArray* x){
   char* s;
   StringBuffer* sb = buf_createDefault();
   buf_put(sb,x->ca.data,x->meta.length);
   s= buf_toString(sb);
   buf_free(sb);
   return s;
}
Beispiel #11
0
record_t *read_record(ALLOC * a, table_t * t, handle_t h)
{
    record_t *r;
    void *buf, *p;
    size_t len = 0;

    if ((r = _alloc_record(t)) == NULL)
        return NULL;
    if ((buf = read_blk(a, h, NULL, &len)) == NULL)
        goto Error;

    p = buf;
    r->prev = b2hdl(p);
    p += 7;
    r->next = b2hdl(p);
    p += 7;
    for (int i = 0; i < t->ncols; i++) {
        switch (t->cols[i].type) {
        case TYPE_INT:
            r->vals[i].v.i = b2int32(p);
            p += 4;
            break;
        case TYPE_FLOAT:
            r->vals[i].v.f = b2float(p);
            p += 4;
            break;
        case TYPE_STRING:
            strlcpy(r->vals[i].v.s, p, t->sizes[i]);
            break;
        default:
            xerrno = FATAL_INVDB;
            goto Error;
        }
    }
    buf_put(a, buf);
    r->self = h;
    return r;

Error:
    if (buf != NULL)
        buf_put(a, buf);
    preserve_errno(_free_record(r));
    return NULL;
}
Beispiel #12
0
int
decode_mountd(u_char *buf, int len, u_char *obuf, int olen)
{
	XDR xdrs;
	struct buf outbuf;
	struct rpc_msg msg;
	struct xid_map *xm;
	struct fhstatus fhstat;
	char *p, *dir;
	int i, hdrlen;

	buf_init(&outbuf, obuf, olen);
	
	if ((hdrlen = rpc_decode(buf, len, &msg)) == 0)
		return (0);

	if (msg.rm_direction == CALL &&
	    msg.rm_call.cb_prog == MOUNTPROG &&
	    msg.rm_call.cb_proc == MOUNTPROC_MNT) {
		xdrmem_create(&xdrs, buf + hdrlen, len - hdrlen, XDR_DECODE);
		dir = NULL;
		if (xdr_string(&xdrs, &dir, MAXPATHLEN)) {
			xid_map_enter(msg.rm_xid, MOUNTPROG, MOUNTVERS,
				      MOUNTPROC_MNT, (void *) dir);
		}
		xdr_destroy(&xdrs);
	}
	else if (msg.rm_direction == REPLY &&
		 (xm = xid_map_find(msg.rm_xid)) != NULL) {
		if (msg.rm_reply.rp_stat == MSG_ACCEPTED &&
		    msg.acpted_rply.ar_stat == SUCCESS) {
			xdrmem_create(&xdrs, buf + hdrlen, len - hdrlen,
				      XDR_DECODE);
			if (xdr_fhstatus(&xdrs, &fhstat)) {
				if (fhstat.fhs_status == 0) {
					buf_putf(&outbuf, "%s [",
						 (char *)xm->data);
					
					p = fhstat.fhstatus_u.fhs_fhandle;
					
					for (i = 0; i < FHSIZE; i++) {
						buf_putf(&outbuf, "%.2x ",
							 p[i] & 0xff);
					}
					buf_put(&outbuf, "]\n", 2);
				}
			}
			xdr_destroy(&xdrs);
		}
		free(xm->data);
		memset(xm, 0, sizeof(*xm));
	}
	buf_end(&outbuf);
	
	return (buf_len(&outbuf));
}
void aesctr_packet_put(struct buf *b) {

    long long pos;
    crypto_uint8 paddinglen;
    struct buf *sendbuf = &packet.sendbuf;

    pos = sendbuf->len;                         /* get position       */
    buf_putnum32(sendbuf, 0);                   /* packet id, for MAC */
    buf_putnum32(sendbuf, 0);                   /* packet length      */
    buf_putnum8(sendbuf, 0);                    /* padding length     */
    buf_put(sendbuf, b->buf, b->len);           /* add data           */

    /* add padding */
    paddinglen  = 2 * BB - ((sendbuf->len - pos - 4) % BB);
    paddinglen += randommod(2) * BB;
    buf_putpadding(sendbuf, paddinglen);

    /* add space for mac */
    buf_putzerobytes(sendbuf, AB);

    /* add packet ID */
    uint32_pack_big(sendbuf->buf + pos, packet.sendpacketid++);

    /* add packet length */
    uint32_pack_big(sendbuf->buf + pos + 4, sendbuf->len - pos - AB - 4 - 4);

    /* add padding length*/
    sendbuf->buf[pos + 8] = paddinglen;

    /* get mac */
    if (sshcrypto_auth(
        sendbuf->buf + sendbuf->len - AB,       /* a    */
        sendbuf->buf + pos,                     /* m    */
        sendbuf->len - pos - AB,                /* mlen */
        packet.servermackey                     /* k    */
        ) != 0) bug_proto();

    /* encrypt */
    if (sshcrypto_stream_xor(
        sendbuf->buf + pos + 4,                 /* c    */
        sendbuf->buf + pos + 4,                 /* m    */
        sendbuf->len - pos - 4 - AB,            /* mlen */
        packet.servernonce,                     /* n    */
        packet.serverkey                        /* k    */
        ) != 0) bug_proto();


    /* remove packet id */
    byte_copy(sendbuf->buf + pos, sendbuf->len - pos - 4, sendbuf->buf + pos + 4);
    sendbuf->len -= 4;

    /* cleanup */
    purge(sendbuf->buf + sendbuf->len, 4);
}
Beispiel #14
0
buf_t *
buf_dup(const buf_t *src)
{
	buf_t	*bp;

	bp = buf_alloc(src->max_size);
	buf_put(bp, src->base + src->head, src->tail - src->head);

	bp->addr = src->addr;
	bp->addrlen = src->addrlen;
	return bp;
}
Beispiel #15
0
int update_record(ALLOC * a, table_t * t, handle_t h, record_t * r)
{
    unsigned char *buf, *p;
    record_t *old;
    size_t len = 0;
    int ret;

    if (_validate_record(a, t, r) < 0)
        return -1;
    if ((old = read_record(a, t, h)) == NULL)
        return -1;

    for (int i = 0; i < t->ncols; i++) {
        if (t->cols[i].unique == COL_NORMAL)
            continue;
        if (_equal(&old->vals[i], &r->vals[i]))
            continue;
        if (t->cols[i].index != 0) {
            if (index_exist(t->cols[i].idx, &r->vals[i])) {
                xerrno = ERR_UNIQ;
                goto Error;
            }
            continue;
        }
        for (handle_t h = t->head; h != 0;) {
            record_t *x;
            int eq;

            if ((x = read_record(a, t, h)) == NULL)
                goto Error;
            h = x->next;
            eq = _equal(&x->vals[i], &r->vals[i]);
            _free_record(x);
            if (eq) {
                xerrno = ERR_UNIQ;
                goto Error;
            }
        }
    }

    if ((buf = read_blk(a, h, NULL, &len)) == NULL)
        goto Error;
    _free_record(old);

    p = record2b_skip(buf, t, r);
    ret = realloc_blk(a, h, buf, p - buf);
    buf_put(a, buf);
    return ret;
Error:
    preserve_errno(_free_record(old));
    return -1;
}
Beispiel #16
0
int _record_setnext(ALLOC * a, handle_t h, handle_t next)
{
    void *buf;
    size_t len = 0;
    int ret;

    if ((buf = read_blk(a, h, NULL, &len)) == NULL)
        return -1;
    hdl2b(buf + 7, next);
    ret = realloc_blk(a, h, buf, len);
    buf_put(a, buf);
    return ret;
}
Beispiel #17
0
/*****************************************************************************
 * Play: play a sound
 *****************************************************************************/
static int Play(dtaudio_output_t *aout, uint8_t *buf, int size) {
    aout_sys_t *sys = (aout_sys_t *) aout->ao_priv;
    int ret = 0;
    //__android_log_print(ANDROID_LOG_DEBUG,TAG, "space:%d level:%d  size:%d  \n",buf_space(&sys->dbt), buf_level(&sys->dbt), size);
    if (buf_space(&sys->dbt) > size) {
        ret = buf_put(&sys->dbt, buf, size);
    }
    sys->samples += ret / bytesPerSample(aout);
    //__android_log_print(ANDROID_LOG_DEBUG,TAG, "add sampels, %d add %d \n",sys->samples, ret / bytesPerSample(aout));

    /* Fill OpenSL buffer */
    WriteBuffer(aout); // will read data in callback
    return ret;
}
Beispiel #18
0
Datei: mfn.c Projekt: berkus/moto
char *mfn_symbolName(MFN *p) {
   if (p->cname == NULL) {
		int i;
		int argc = vec_size(p->argv);
		StringBuffer *buf = buf_create(32);
	
		/* If the classname is not null then this is a method and the classname 
			should prefix the generated cname */
			
		if (p->classn != NULL)
			 buf_printf(buf, "_%s",p->classn);
		
		/* If the fname starts with '~' (i.e. this is a destructor) convert it 
			into an '_' */
		
		if (p->fname[0] == '~')
			 buf_printf(buf,"__%s__", p->fname+1);
		else     
			 buf_printf(buf, "_%s__", p->fname);
       
      for (i = 0; i < argc; i++) {
      	FNArg *arg = (FNArg *)vec_get(p->argv, i);
      	int l = strlen(arg->type);
      
			/* Output one P for each dimension of an array argument */
			while(arg->type[l-1] == ']'){ buf_putc(buf,'P'); l -= 2; }
				
			/* For built in types output the first letter of the 
				type name for the argument */
			
			if(l == 3 && !strncmp(arg->type,"int",l)) buf_putc(buf,'i');
			else if(l == 5 && !strncmp(arg->type,"float",l)) buf_putc(buf,'f');
			else if(l == 6 && !strncmp(arg->type,"double",l)) buf_putc(buf,'d');
			else if(l == 4 && !strncmp(arg->type,"char",l)) buf_putc(buf,'c');
			else if(l == 4 && !strncmp(arg->type,"long",l)) buf_putc(buf,'l');
			else if(l == 7 && !strncmp(arg->type,"boolean",l)) buf_putc(buf,'b');
			else if(l == 4 && !strncmp(arg->type,"byte",l)) buf_putc(buf,'y');
			else if(l == 6 && !strncmp(arg->type,"String",l)) buf_putc(buf,'S');
			else if(l == 6 && !strncmp(arg->type,"Object",l)) buf_putc(buf,'O');
			else if(arg->type[l-1] == ')') buf_putc(buf,'F');
			else { buf_puti(buf, l); buf_put(buf,arg->type,l); }
			  
      }   

      p->cname = buf_toString(buf);
      buf_free(buf);
   }
   return p->cname;
}
Beispiel #19
0
buf_t
buf_getword(buf_t buf, void *sep, int len)
{
	buf_t b;
	int off;
	
	if ((off = buf_index(buf, sep, len)) < 0)
		return (NULL);

	if ((b = buf_new(off)) != NULL) {
		buf_put(b, buf_ptr(buf), off);
		buf_end(b);
		buf_skip(buf, off + len);
	}
	return (b);
}
Beispiel #20
0
void *_read_blk(ALLOC * a, handle_t handle, void *buf, size_t * len)
{
	if (handle == 0)
		return NULL;
	off_t offset;
	size_t need;
	unsigned char bytes[ATOM_LEN];
	int newbuf = 0, redirect = 0;

 Retry:
	offset = hdl2off(handle);
	if (readat(a->fd, bytes, 8, offset) != 8)
		return NULL;
	switch (bytes[0]) {
	case CTBLK_SHORT:
		need = (size_t) bytes[1];
		offset += 2;
		break;
	case CTBLK_LONG:
		need = (size_t) b2uint16(&bytes[1]);
		offset += 3;
		break;
	case REBLK:
		if (redirect)	// allow redirect only once
			return NULL;
		handle = b2hdl(&bytes[1]);
		redirect = 1;
		goto Retry;
	default:
		xerrno = FATAL_BLKTAG;
		return NULL;
	}
	if (buf == NULL || need > *len) {
		if ((buf = buf_get(a, need)) == NULL)
			return NULL;
		*len = need;
		newbuf = 1;
	}
	if (readat(a->fd, buf, need, offset) != need) {
		if (newbuf)
			buf_put(a, buf);
		return NULL;
	}
	return buf;
}
Beispiel #21
0
buf_t
buf_getbuf(buf_t buf, int offset, int len)
{
	buf_t b;
	
	if (buf->offset + offset + len > buf->end)
		return (NULL);

	buf_skip(buf, offset);
	
	if ((b = buf_new(len)) != NULL) {
		buf_put(b, buf_ptr(buf), len);
		buf_end(b);
	}
	buf_skip(buf, len);
	
	return (b);
}
Beispiel #22
0
static int send_disconnect_msg(ni_t *ni, conn_t *conn)
{
    req_hdr_t *hdr;
    int err;
    buf_t *buf;

    if (conn->transport.type != CONN_TYPE_RDMA)
        return PTL_OK;

    err = buf_alloc(ni, &buf);
    if (unlikely(err)) {
        return err;
    }

    assert(buf->type == BUF_FREE);

    buf->type = BUF_SEND;
    buf->conn = conn;
    buf->length = sizeof(req_hdr_t);

    /* Inline if possible and don't request a completion because we
     * don't care. */
    buf->event_mask = XX_INLINE | XX_SIGNALED;

    hdr = (req_hdr_t *) buf->data;

    hdr->h1.operation = OP_RDMA_DISC;
    hdr->h1.version = PTL_HDR_VER_1;
    hdr->h1.ni_type = conn->obj.obj_ni->ni_type;
    hdr->h1.src_nid = cpu_to_le32(ni->id.phys.nid);
    hdr->h1.src_pid = cpu_to_le32(ni->id.phys.pid);

#if IS_PPE
    hdr->h1.physical = !!(ni->options & PTL_NI_PHYSICAL);
#endif

    set_buf_dest(buf, conn);

    err = conn->transport.send_message(buf, 0);

    buf_put(buf);

    return err;
}
Beispiel #23
0
/*
 * Change cachepct
 */
void
bufadjust(int newbufpages)
{
	struct buf *bp;
	int s;

	if (newbufpages < buflowpages)
		newbufpages = buflowpages;

	s = splbio();
	bufpages = newbufpages;

	/*
	 * We are allowed to use up to the reserve
	 */
	targetpages = bufpages - RESERVE_PAGES;

	/*
	 * Shrinking the cache happens here only if someone has manually
	 * adjusted bufcachepercent - or the pagedaemon has told us
	 * to give back memory *now* - so we give it all back.
	 */
	while ((bp = bufcache_getcleanbuf()) &&
	    (bcstats.numbufpages > targetpages)) {
		bufcache_take(bp);
		if (bp->b_vp) {
			RB_REMOVE(buf_rb_bufs,
			    &bp->b_vp->v_bufs_tree, bp);
			brelvp(bp);
		}
		buf_put(bp);
	}

	/*
	 * Wake up the cleaner if we have lots of dirty pages,
	 * or if we are getting low on buffer cache kva.
	 */
	if ((UNCLEAN_PAGES >= hidirtypages) ||
	    bcstats.kvaslots_avail <= 2 * RESERVE_SLOTS)
		wakeup(&bd_req);

	splx(s);
}
/*
 * buf_write() processes write requests.
 *     Firstly, this checks the correctness of parameters,
 *     and calls buf_put() to process actual requests according to policy
 *     (POLICY_WRITE_THROUGH or POLICY_DELAYED_WRITE).
 *
 * parameters:
 *     pdev:		device descriptor
 *     buffer:  	a user buffer that should hold the block_no block
 *     block_no:	block number to be served
 */
int buf_write(struct devsw *pdev, char *buffer, int block_no) {
	disk_desc *ptr;
	dsk_buffer_p target;
	int code;
	STATWORD ps;

	disable(ps);
	if(!pdev || !buffer) {
		restore(ps);
		return SYSERR;
	}

	ptr = (disk_desc *)pdev -> dvioblk;
	if(block_no < 0 || block_no > ptr -> logical_blocks) {
		restore(ps);
		return SYSERR;
	}
	restore(ps);
	code = buf_put(pdev, block_no, buffer, PA4_WRITE_POLICY);
	//signal(ptr->sem_b);
	return code;
}
Beispiel #25
0
int main(int argc, char **argv) {

    char *x;
    const char *keydir = 0;
    long long i;
    struct pollfd p[6];
    struct pollfd *q;
    struct pollfd *watch0;
    struct pollfd *watch1;
    struct pollfd *watchtochild;
    struct pollfd *watchfromchild1;
    struct pollfd *watchfromchild2;
    struct pollfd *watchselfpipe;
    int exitsignal, exitcode;

    signal(SIGPIPE, SIG_IGN);
    signal(SIGALRM, timeout);

    log_init(0, "tinysshd", 0, 0);

    if (argc < 2) die_usage(USAGE);
    if (!argv[0]) die_usage(USAGE);
    for (;;) {
        if (!argv[1]) break;
        if (argv[1][0] != '-') break;
        x = *++argv;
        if (x[0] == '-' && x[1] == 0) break;
        if (x[0] == '-' && x[1] == '-' && x[2] == 0) break;
        while (*++x) {
            if (*x == 'q') { flagverbose = 0; continue; }
            if (*x == 'Q') { flagverbose = 1; continue; }
            if (*x == 'v') { if (flagverbose >= 2) flagverbose = 3; else flagverbose = 2; continue; }
            if (*x == 'o') { cryptotypeselected |= sshcrypto_TYPEOLDCRYPTO; continue; }
            if (*x == 'O') { cryptotypeselected &= ~sshcrypto_TYPEOLDCRYPTO; continue; }
            if (*x == 's') { cryptotypeselected |= sshcrypto_TYPENEWCRYPTO; continue; }
            if (*x == 'S') { cryptotypeselected &= ~sshcrypto_TYPENEWCRYPTO; continue; }
            if (*x == 'p') { cryptotypeselected |= sshcrypto_TYPEPQCRYPTO; continue; }
            if (*x == 'P') { cryptotypeselected &= ~sshcrypto_TYPEPQCRYPTO; continue; }
            if (*x == 'l') { flaglogger = 1; continue; }
            if (*x == 'L') { flaglogger = 0; continue; }
            if (*x == 'x') {
                if (x[1]) { channel_subsystem_add(x + 1); break; }
                if (argv[1]) { channel_subsystem_add(*++argv); break; }
            }

            die_usage(USAGE);
        }
    }
    keydir = *++argv; if (!keydir) die_usage(USAGE);

    log_init(flagverbose, "tinysshd", 1, flaglogger);

    connectioninfo(channel.localip, channel.localport, channel.remoteip, channel.remoteport);
    log_i4("connection from ", channel.remoteip, ":", channel.remoteport);

    channel_subsystem_log();

    global_init();

    blocking_disable(0);
    blocking_disable(1);
    blocking_disable(2);

    /* get server longterm keys */
    fdwd = open_cwd();
    if (fdwd == -1) die_fatal("unable to open current directory", 0, 0);
    if (chdir(keydir) == -1) die_fatal("unable to chdir to", keydir, 0);

    for (i = 0; sshcrypto_keys[i].name; ++i) sshcrypto_keys[i].sign_flagserver |= sshcrypto_kexs[i].cryptotype & cryptotypeselected;
    for (i = 0; sshcrypto_keys[i].name; ++i) sshcrypto_keys[i].sign_flagclient |= sshcrypto_kexs[i].cryptotype & cryptotypeselected;
    for (i = 0; sshcrypto_kexs[i].name; ++i) sshcrypto_kexs[i].flagenabled |= sshcrypto_kexs[i].cryptotype & cryptotypeselected;
    for (i = 0; sshcrypto_ciphers[i].name; ++i) sshcrypto_ciphers[i].flagenabled |= sshcrypto_ciphers[i].cryptotype & cryptotypeselected;

    /* read public keys */
    for (i = 0; sshcrypto_keys[i].name; ++i) {
        if (!sshcrypto_keys[i].sign_flagserver) continue;
        if (load(sshcrypto_keys[i].sign_publickeyfilename, sshcrypto_keys[i].sign_publickey, sshcrypto_keys[i].sign_publickeybytes) == -1) {
            sshcrypto_keys[i].sign_flagserver = 0;
            if (errno == ENOENT) continue;
            die_fatal("unable to read public key from file", keydir, sshcrypto_keys[i].sign_publickeyfilename);
        }
    }

    if (fchdir(fdwd) == -1) die_fatal("unable to change directory to working directory", 0, 0);
    close(fdwd);

    /* set timeout */
    alarm(60);

    /* send and receive hello */
    if (!packet_hello_send()) die_fatal("unable to send hello-string", 0, 0);
    if (!packet_hello_receive()) die_fatal("unable to receive hello-string", 0, 0);

    /* send and receive kex */
    if (!packet_kex_send()) die_fatal("unable to send kex-message", 0, 0);
    if (!packet_kex_receive()) die_fatal("unable to receive kex-message", 0, 0);

rekeying:
    /* rekeying */
    alarm(60);
    if (packet.flagrekeying == 1) {
        buf_purge(&packet.kexrecv);
        buf_put(&packet.kexrecv, b1.buf, b1.len);
        if (!packet_kex_send()) die_fatal("unable to send kex-message", 0, 0);
    }

    /* send and receive kexdh */
    if (!packet_kexdh(keydir, &b1, &b2)) die_fatal("unable to subprocess kexdh", 0, 0);

    if (packet.flagkeys) log_d1("rekeying: done");
    packet.flagkeys = 1;

    /* note: comunication is encrypted */

    /* authentication + authorization */
    if (packet.flagauthorized == 0) {
        if (!packet_auth(&b1, &b2)) die_fatal("authentication failed", 0, 0);
        packet.flagauthorized = 1;
    }

    /* note: user is authenticated and authorized */
    alarm(3600);

    /* main loop */
    for (;;) {
        if (channel_iseof())
            if (!packet.sendbuf.len)
                if (packet.flagchanneleofreceived)
                    break;

        watch0 = watch1 = 0;
        watchtochild = watchfromchild1 = watchfromchild2 = 0;
        watchselfpipe = 0;

        q = p;

        if (packet_sendisready()) { watch1 = q; q->fd = 1; q->events = POLLOUT; ++q; }
        if (packet_recvisready()) { watch0 = q; q->fd = 0; q->events = POLLIN;  ++q; }

        if (channel_writeisready()) { watchtochild = q; q->fd = channel_getfd0(); q->events = POLLOUT; ++q; }
        if (channel_readisready() && packet_putisready()) { watchfromchild1 = q; q->fd = channel_getfd1(); q->events = POLLIN; ++q; }
        if (channel_extendedreadisready() && packet_putisready()) { watchfromchild2 = q; q->fd = channel_getfd2(); q->events = POLLIN; ++q; }

        if (selfpipe[0] != -1) { watchselfpipe = q; q->fd = selfpipe[0]; q->events = POLLIN; ++q; }

        if (poll(p, q - p, 60000) < 0) {
            watch0 = watch1 = 0;
            watchtochild = watchfromchild1 = watchfromchild2 = 0;
            watchselfpipe = 0;
        }

        else {
            if (watch0) if (!watch0->revents) watch0 = 0;
            if (watch1) if (!watch1->revents) watch1 = 0;
            if (watchfromchild1) if (!watchfromchild1->revents) watchfromchild1 = 0;
            if (watchfromchild2) if (!watchfromchild2->revents) watchfromchild2 = 0;
            if (watchtochild) if (!watchtochild->revents) watchtochild = 0;
            if (watchselfpipe) if (!watchselfpipe->revents) watchselfpipe = 0;
        }

        if (watchtochild) {

            /* write data to child */
            if (!channel_write()) die_fatal("unable to write data to child", 0, 0);

            /* try to adjust window */
            if (!packet_channel_send_windowadjust(&b1)) die_fatal("unable to send data to network", 0, 0);
        }

        /* read data from child */
        if (watchfromchild1) packet_channel_send_data(&b2);
        if (watchfromchild2) packet_channel_send_extendeddata(&b2);

        /* check child */
        if (channel_iseof()) {
            if (selfpipe[0] == -1) if (open_pipe(selfpipe) == -1) die_fatal("unable to open pipe", 0, 0);
            signal(SIGCHLD, trigger);
            if (channel_waitnohang(&exitsignal, &exitcode)) {
                packet_channel_send_eof(&b2);
                if (!packet_channel_send_close(&b2, exitsignal, exitcode)) die_fatal("unable to close channel", 0, 0);
            }
        }

        /* send data to network */
        if (watch1) if (!packet_send()) die_fatal("unable to send data to network", 0, 0);

        /* receive data from network */
        if (watch0) {
            alarm(3600); /* refresh timeout */
            if (!packet_recv()) {
                if (channel_iseof()) break; /* XXX */
                die_fatal("unable to receive data from network", 0, 0);
            }
        }

        /* process packets */
        for (;;) {

            if (!packet_get(&b1, 0)) {
                if (!errno) break;
                die_fatal("unable to get packets from network", 0, 0);
            }
            if (b1.len < 1) break; /* XXX */

            switch (b1.buf[0]) {
                case SSH_MSG_CHANNEL_OPEN:
                    if (!packet_channel_open(&b1, &b2)) die_fatal("unable to open channel", 0, 0);
                    break;
                case SSH_MSG_CHANNEL_REQUEST:
                    if (!packet_channel_request(&b1, &b2)) die_fatal("unable to handle channel-request", 0, 0);
                    break;
                case SSH_MSG_CHANNEL_DATA:
                    if (!packet_channel_recv_data(&b1)) die_fatal("unable to handle channel-data", 0, 0);
                    break;
                case SSH_MSG_CHANNEL_EXTENDED_DATA:
                    if (!packet_channel_recv_extendeddata(&b1)) die_fatal("unable to handle channel-extended-data", 0, 0);
                    break;
                case SSH_MSG_CHANNEL_WINDOW_ADJUST:
                    if (!packet_channel_recv_windowadjust(&b1)) die_fatal("unable to handle channel-window-adjust", 0, 0);
                    break;
                case SSH_MSG_CHANNEL_EOF:
                    if (!packet_channel_recv_eof(&b1)) die_fatal("unable to handle channel-eof", 0, 0);
                    break;
                case SSH_MSG_CHANNEL_CLOSE:
                    if (!packet_channel_recv_close(&b1)) die_fatal("unable to handle channel-close", 0, 0);
                    break;
                case SSH_MSG_KEXINIT:
                    goto rekeying;
                default:
                    if (!packet_unimplemented(&b1)) die_fatal("unable to send SSH_MSG_UNIMPLEMENTED message", 0, 0);
            }
        }
    }

    log_i1("finished");
    global_die(0); return 111;
}
Beispiel #26
0
int
decode_mmxp(u_char *buf, int len, u_char *obuf, int olen)
{
	struct buf inbuf, outbuf;
	u_char *p, c;
	u_int32_t i;
	int encrypt;

	buf_init(&inbuf, buf, len);
	buf_init(&outbuf, obuf, len);

	while ((i = buf_index(&inbuf, "\x00\x00\x24\x55", 4)) != -1) {
		buf_skip(&inbuf, i + 4);

		if (buf_cmp(&inbuf, "\x7f\xff", 2) == 0)
			encrypt = 1;
		else if (buf_cmp(&inbuf, "\xff\xff", 2) == 0)
			encrypt = 0;
		else continue;

		buf_skip(&inbuf, 4);
		
		/* LPPPg? */
		if (buf_get(&inbuf, &i, sizeof(i)) < 0)
			break;

		i = ntohl(i);
		if (buf_skip(&inbuf, i + 4 + 4) < 0)
			continue;

		/* Server. */
		if (buf_get(&inbuf, &c, 1) != 1) break;
		if (buf_len(&inbuf) < c) break;
		
		buf_put(&outbuf, buf_ptr(&inbuf), c);
		buf_put(&outbuf, "\n", 1);
		buf_skip(&inbuf, c + 4);
		
		/* Username. */
		if (buf_get(&inbuf, &c, 1) != 1) break;
		if (buf_len(&inbuf) < c) break;
		
		buf_put(&outbuf, buf_ptr(&inbuf), c);
		buf_put(&outbuf, "\n", 1);
		buf_skip(&inbuf, c + 4);
	
		/* Password. */
		if (buf_get(&inbuf, &c, 1) != 1) break;
		if (buf_len(&inbuf) < c) break;

		p = buf_ptr(&inbuf);
		
		if (encrypt) {
			for (i = 0; i < c; i++)
				p[i] ^= mm_xor[i % (sizeof(MM_SECRET) - 1)];
		}
		buf_put(&outbuf, p, c);
		buf_put(&outbuf, "\n", 1);
	}
	buf_end(&outbuf);
		
	return (buf_len(&outbuf));
}
Beispiel #27
0
// tests
////////////////////////////////////////////////////////////////////////////////
int test_buf_put_buf_get() {
    // Description
    // This function tests the buf_put and buf_get functions.
    //
    // Returns
    // test_buf_put_buf_get returns 0 on successful completion of all tests or
    // -1 in case of any test or itself failing.

    // variable declaration
    char string[MAX_STRING_LENGTH + 1];
    int string_length;
    char c;
    int num_tests;  // number of tests
    int num_passed;  // number of tests passed
    int failed;  // boolean indicator of whether any test has failed
    int i;  // generic counter

    printf("testing buf_put, buf_get\n");

    num_tests = 0;
    num_passed = 0;

    // test 01
    num_tests++;
    failed = 0;

    // Put and get the characters of a string in and out of the buffer one by
    // one.
    strcpy(string, "Hello World!");
    string_length = strlen(string);
    for (i = 0; i < string_length; i++) {
        buf_put(string[i]);
        buf_get(&c);
        if (c != string[i]) {
            failed = 1;
        }
        printf("%c", c);
    }
    printf("\n");

    if (!failed) {
        num_passed++;
    }

    // test 02
    num_tests++;
    failed = 0;

    // Put all the characters of a string in the buffer until it is full and
    // subsequently get them out of it.
    strcpy(string, "Hello World!");
    string_length = strlen(string);
    for (i = 0; i < string_length; i++) {
        buf_put(string[i]);
    }
    for (i = 0; (i < string_length) && (i < (cb_size - 1)); i++) {
        buf_get(&c);
        if (c != string[i]) {
            failed = 1;
        }
        printf("%c", c);
    }
    printf("\n");

    if (!failed) {
        num_passed++;
    }

    if (num_passed == num_tests) {
        printf("\tall tests passed\n");
        return 0;
    } else {
        printf("\tat least one test failed\n");
        return -1;
    }
}
static void *audio_decode_loop (void *arg)
{
    int ret;
    dtaudio_decoder_t *decoder = (dtaudio_decoder_t *) arg;
    dtaudio_para_t *para = &decoder->aparam;
    dt_av_frame_t frame;
    ad_wrapper_t *wrapper = decoder->wrapper;
    dtaudio_context_t *actx = (dtaudio_context_t *) decoder->parent;
    dt_buffer_t *out = &actx->audio_decoded_buf;
    int declen, fill_size;
    
    //for some type audio, can not read completly frame 
    uint8_t *frame_data = NULL; // point to frame start
    uint8_t *rest_data = NULL;
    int frame_size = 0;
    int rest_size = 0;

    int used;                   // used size after every decode ops

    adec_ctrl_t *pinfo = &decoder->info;
    memset(pinfo,0,sizeof(*pinfo));
    pinfo->channels = para->channels;
    pinfo->samplerate = para->samplerate;
    pinfo->outptr = malloc(MAX_ONE_FRAME_OUT_SIZE);
    pinfo->outsize = MAX_ONE_FRAME_OUT_SIZE;

    dt_info (TAG, "[%s:%d] AUDIO DECODE START \n", __FUNCTION__, __LINE__);
    do
    {
        //maybe receive exit cmd in idle status, so exit prior to idle
        if (decoder->status == ADEC_STATUS_EXIT) 
        {
            dt_debug (TAG, "[%s:%d] receive decode loop exit cmd \n", __FUNCTION__, __LINE__);
            if (frame_data)
                free (frame_data);
            if (rest_data)
                free (rest_data);
            break;
        }

        if (decoder->status == ADEC_STATUS_IDLE)
        {
            dt_info (TAG, "[%s:%d] Idle status ,please wait \n", __FUNCTION__, __LINE__);
            usleep (100);
            continue;
        }

        /*read frame */
        if (!decoder->parent)
        {
            usleep (10000);
            dt_info (TAG, "[%s:%d] decoder parent is NULL \n", __FUNCTION__, __LINE__);
            continue;
        }
        ret = audio_read_frame (decoder->parent, &frame);
        if (ret < 0 || frame.size <= 0)
        {
            usleep (1000);
            dt_debug (TAG, "[%s:%d] dtaudio decoder loop read frame failed \n", __FUNCTION__, __LINE__);
            continue;
        }
        //read ok,update current pts, clear the buffer size
        if (frame.pts >= 0)
        {
            if (decoder->pts_first == -1)
            {
                if(frame.pts == DT_NOPTS_VALUE)
                    frame.pts = 0;
                decoder->pts_first = pts_exchange (decoder, frame.pts);
                dt_info (TAG, "first frame pts:%lld dts:%lld duration:%d size:%d\n", decoder->pts_first, frame.dts, frame.duration, frame.size);
            }
            decoder->pts_current = pts_exchange (decoder, frame.pts);
            dt_debug (TAG, "pkt pts:%lld current:%lld duration:%d pts_s:%lld dts:%lld buf_size:%d \n", frame.pts, decoder->pts_current, frame.duration, frame.pts / 90000, frame.dts, decoder->pts_buffer_size);
            decoder->pts_last_valid = decoder->pts_current;
            decoder->pts_buffer_size = 0;
        }
        //repack the frame
        if (frame_data)
        {
            free (frame_data);
            frame_data = NULL;
            frame_size = 0;
        }
        if (rest_size)
            frame_data = malloc (frame.size + rest_size);
        else
            frame_data = frame.data;
        if (!frame_data)
        {
            dt_error (TAG, "malloc audio frame failed ,we will lost one frame\n");
            if (rest_data)
                free (rest_data);
            rest_size = 0;
            continue;
        }

        if (rest_size)          // no rest data
        {
            dt_debug (TAG, "left %d byet last time\n", rest_size);
            memcpy (frame_data, rest_data, rest_size);
            free (rest_data);
            rest_data = NULL;
            memcpy (frame_data + rest_size, frame.data, frame.size);
        }

        frame_size = frame.size + rest_size;
        rest_size = 0;
        used = 0;
        declen = 0;

        pinfo->inptr = frame_data;
        pinfo->inlen = frame_size;
        pinfo->outlen = 0; 

        //free pkt
        frame.data = NULL;
        frame.size = 0;

      DECODE_LOOP:
        if (decoder->status == ADEC_STATUS_EXIT)
        {
            dt_info (TAG, "[%s:%d] receive decode loop exit cmd \n", __FUNCTION__, __LINE__);
            if (frame_data)
                free (frame_data);
            break;
        }
        /*decode frame */
        pinfo->consume = declen;
        used = wrapper->decode_frame (wrapper, pinfo);
        if (used < 0)
        {
            decoder->decode_err_cnt++;
            /*
             * if decoder is ffmpeg,do not restore data if decode failed
             * if decoder is not ffmpeg, restore raw stream packet if decode failed
             * */
            if (!strcmp (wrapper->name, "ffmpeg audio decoder"))
            {
                dt_error (TAG, "[%s:%d] ffmpeg failed to decode this frame, just break\n", __FUNCTION__, __LINE__);
                decoder->decode_offset += pinfo->inlen;
            }
            continue;
        }
        else if (used == 0 && pinfo->outlen == 0) // used == 0 && out == 0 means need more data
        {
            //maybe need more data
            rest_data = malloc (pinfo->inlen);
            if (rest_data == NULL)
            {
                dt_error ("[%s:%d] rest_data malloc failed\n", __FUNCTION__, __LINE__);
                rest_size = 0;  //skip this frame
                continue;
            }
            memcpy (rest_data, pinfo->inptr, pinfo->inlen);
            rest_size = pinfo->inlen;
            dt_info (TAG, "Maybe we need more data\n");
            continue;
        }
        declen += used;
        pinfo->inlen -= used;
        decoder->decode_offset += used;
        decoder->pts_cache_size = pinfo->outlen;
        decoder->pts_buffer_size += pinfo->outlen;
        if (pinfo->outlen == 0)      //get no data, maybe first time for init
            dt_info (TAG, "GET NO PCM DECODED OUT,used:%d \n",used);

        fill_size = 0;
      REFILL_BUFFER:
        if (decoder->status == ADEC_STATUS_EXIT)
            goto EXIT;
        /*write pcm */
        if (buf_space (out) < pinfo->outlen)
        {
            dt_debug (TAG, "[%s:%d] output buffer do not left enough space ,space=%d level:%d outsie:%d \n", __FUNCTION__, __LINE__, buf_space (out), buf_level (out), pinfo->outlen);
            usleep (1000);
            goto REFILL_BUFFER;
        }
        ret = buf_put (out, pinfo->outptr + fill_size, pinfo->outlen);
        fill_size += ret;
        pinfo->outlen -= ret;
        decoder->pts_cache_size = pinfo->outlen;
        if (pinfo->outlen > 0)
            goto REFILL_BUFFER;

        if (pinfo->inlen)
            goto DECODE_LOOP;
    }
    while (1);
  EXIT:
    dt_info (TAG, "[file:%s][%s:%d]decoder loop thread exit ok\n", __FILE__, __FUNCTION__, __LINE__);
    /* free adec_ctrl_t buf */
    if(pinfo->outptr)
        free(pinfo->outptr);
    pinfo->outlen = pinfo->outsize = 0;
    pthread_exit (NULL);
    return NULL;
}
Beispiel #29
0
int packet_auth(struct buf *b, struct buf *b2) {

    crypto_uint8 ch, flagsignature;
    long long pos, i, count, sign_bytes = 0;
    crypto_uint32 len;
    const char *pkname;
    int (*sign_open)(unsigned char *,unsigned long long *,const unsigned char *,unsigned long long,const unsigned char *) = 0;
    int (*parsesignpk)(unsigned char *, const unsigned char *, long long) = 0;
    int (*parsesignature)(unsigned char *, const unsigned char *, long long) = 0;
    void (*putsignpk)(struct buf *, const unsigned char *) = 0;
    void (*putsignpkbase64)(struct buf *, const unsigned char *) = 0;
    unsigned char pk[sshcrypto_sign_PUBLICKEYMAX];
    unsigned char sig[sshcrypto_sign_MAX];
    unsigned long long smlen;

    buf_purge(b);

    /* parse "ssh-userauth" */
    pos = 0;
    if (!packet_getall(b, SSH_MSG_SERVICE_REQUEST)) bug();
    pos = packetparser_uint8(b->buf, b->len, pos, &ch);       /* SSH_MSG_SERVICE_REQUEST */
    if (ch != SSH_MSG_SERVICE_REQUEST) bug_proto();
    pos = packetparser_uint32(b->buf, b->len, pos, &len);     /* "ssh-userauth" */
    if (len != 12) bug_proto();
    pos = packetparser_skip(b->buf, b->len, pos, len);
    if (!byte_isequal(b->buf + pos - len, len, "ssh-userauth")) bug_proto();
    pos = packetparser_end(b->buf, b->len, pos);

    /* send service accept */
    b->buf[0] = SSH_MSG_SERVICE_ACCEPT;
    packet_put(b);
    if (!packet_sendall()) bug();


    for (count = 0; count < 32; ++count) {
        /* receive userauth request */
        pkname = "unknown";
        pos = 0;
        buf_purge(b);
        if (!packet_getall(b, SSH_MSG_USERAUTH_REQUEST)) bug();
        pos = packetparser_uint8(b->buf, b->len, pos, &ch);         /* SSH_MSG_USERAUTH_REQUEST */
        if (ch != SSH_MSG_USERAUTH_REQUEST) bug_proto();
        pos = packetparser_uint32(b->buf, b->len, pos, &len);       /* name */
        if (len >= PACKET_NAMESIZE) bug_proto();
        pos = packetparser_copy(b->buf, b->len, pos, (unsigned char *)packet.name, len);
        packet.name[len] = 0;
        pos = packetparser_uint32(b->buf, b->len, pos, &len);       /* "ssh-connection" */
        if (len != 14) bug_proto();
        pos = packetparser_skip(b->buf, b->len, pos, len);
        if (!byte_isequal(b->buf + pos - len, len, "ssh-connection")) bug_proto();

        pos = packetparser_uint32(b->buf, b->len, pos, &len);       /* publickey/password/hostbased/none */
        pos = packetparser_skip(b->buf, b->len, pos, len);

        if (str_equaln((char *)b->buf + pos - len, len, "none")) pkname = "none";
        if (str_equaln((char *)b->buf + pos - len, len, "password")) pkname = "password";
        if (str_equaln((char *)b->buf + pos - len, len, "hostbased")) pkname = "hostbased";
        if (str_equaln((char *)b->buf + pos - len, len, "publickey")) {
            pos = packetparser_uint8(b->buf, b->len, pos, &flagsignature);

            pos = packetparser_uint32(b->buf, b->len, pos, &len);   /* public key algorithm name */
            pos = packetparser_skip(b->buf, b->len, pos, len);
            if (b->buf[pos] != 0) bug_proto();
            pkname = (char *)b->buf + pos - len; /* XXX */

            sign_open = 0; parsesignpk = 0; putsignpk = 0; putsignpkbase64 = 0; parsesignature = 0; sign_bytes = 0;
            for (i = 0; sshcrypto_keys[i].name; ++i) {
                if (!sshcrypto_keys[i].sign_flagclient) continue;
                if (!str_equaln(pkname, len, sshcrypto_keys[i].name)) continue;
                pkname = sshcrypto_keys[i].name;
                sign_open = sshcrypto_keys[i].sign_open;
                parsesignature = sshcrypto_keys[i].parsesignature;
                parsesignpk = sshcrypto_keys[i].parsesignpk;
                putsignpk = sshcrypto_keys[i].buf_putsignpk;
                putsignpkbase64 = sshcrypto_keys[i].buf_putsignpkbase64;
                sign_bytes = sshcrypto_keys[i].sign_bytes;
                break;
            }
            if (sign_open && parsesignpk && putsignpk && putsignpkbase64 && parsesignature) {
                pos = packetparser_uint32(b->buf, b->len, pos, &len);   /* public key blob */
                pos = packetparser_skip(b->buf, b->len, pos, len);
                if (!parsesignpk(pk, b->buf + pos - len, len)) bug_proto();

                if (!flagsignature) {
                    /* 'publickey' ... without signature */
                    buf_purge(b);
                    buf_putnum8(b, SSH_MSG_USERAUTH_PK_OK);
                    buf_putstring(b, pkname);
                    putsignpk(b, pk);
                    packet_put(b);
                    if (!packet_sendall()) bug();
                    continue;
                }


                /* 'publickey' ... with signature */
                pos = packetparser_uint32(b->buf, b->len, pos, &len);   /* signature blob */
                pos = packetparser_skip(b->buf, b->len, pos, len);
                if (!parsesignature(sig, b->buf + pos - len, len)) bug_proto();
                pos = packetparser_end(b->buf, b->len, pos);
                purge(b->buf + b->len - len - 4, len + 4);
                b->len -= len + 4;


                /* authenticate user - verify signature */
                buf_purge(b2);
                buf_put(b2, sig, sign_bytes);
                buf_putstringlen(b2, packet.sessionid, sshcrypto_hash_bytes);
                buf_put(b2, b->buf, b->len);

                buf_purge(b);
                if (b->alloc <= b2->len) bug_nomem();
                if (sign_open(b->buf, &smlen, b2->buf, b2->len, pk) != 0) { errno = EAUTH; bug(); }
                b->len = smlen; buf_purge(b);

                /* authorize user -  using authorized_keys */
                buf_purge(b);
                putsignpkbase64(b, pk);
                buf_putnum8(b, 0);
                if (subprocess_auth(packet.name, pkname, (char *)b->buf) == 0) goto authorized;
            }
        }

        /* reject */
        log_i5("auth: ", packet.name, ": ", pkname, " rejected");
        buf_purge(b);
        buf_putnum8(b, SSH_MSG_USERAUTH_FAILURE);
        buf_putstring(b,"publickey");
        buf_putnum8(b, 0);
        packet_put(b);
        if (!packet_sendall()) bug();
    }
    log_w1("auth: too many authentication tries");
    return 0;


authorized:
    /* authenticated + authorized */
    log_i5("auth: ", packet.name, ": ", pkname, " accepted");
    buf_purge(b);
    buf_putnum8(b, SSH_MSG_USERAUTH_SUCCESS);
    buf_putstring(b,"ssh-connection");
    packet_put(b);
    if (!packet_sendall()) bug();

    purge(pk, sizeof pk);
    purge(sig, sizeof sig);
    return 1;
}
Beispiel #30
0
/* Put null-terminated chars to the end of a buffer. */
int
buf_puts(struct buf *buf, const char *s)
{
    return buf_put(buf, (char *)s, strlen(s));
}