#include "krb_locl.h"

RCSID("$Id: create_ticket.c,v 1.7 1996/06/17 15:57:32 joda Exp $");

/*
 * Create ticket takes as arguments information that should be in a
 * ticket, and the KTEXT object in which the ticket should be
 * constructed.  It then constructs a ticket and returns, leaving the
 * newly created ticket in tkt.
 * The length of the ticket is a multiple of
 * eight bytes and is in tkt->length.
 *
 * If the ticket is too long, the ticket will contain nulls.
 *
 * The corresponding routine to extract information from a ticket it
 * decomp_ticket.  When changes are made to this routine, the
 * corresponding changes should also be made to that file.
 *
 * The packet is built in the following format:
 * 
 * 			variable
 * type			or constant	   data
 * ----			-----------	   ----
 *
 * tkt->length		length of ticket (multiple of 8 bytes)
 * 
 * tkt->dat:
 * 
 * unsigned char	flags		   namely, HOST_BYTE_ORDER
 * 
 * string		pname		   client's name
 * 
 * string		pinstance	   client's instance
 * 
 * string		prealm		   client's realm
 * 
 * 4 bytes		paddress	   client's address
 * 
 * 8 bytes		session		   session key
 * 
 * 1 byte		life		   ticket lifetime
 * 
 * 4 bytes		time_sec	   KDC timestamp
 * 
 * string		sname		   service's name
 * 
 * string		sinstance	   service's instance
 * 
 * <=7 bytes		null		   null pad to 8 byte multiple
 *
 */

/* Gets filled in by the ticket */
/* Various Kerberos flags */
/* Principal's name */
/* Principal's instance */
/* Principal's authentication domain */
/* Net address of requesting entity */
/* Session key inserted in ticket */
/* Lifetime of the ticket */
/* Issue time and date */
/* Service Name */
/* Instance Name */
/* Service's secret key */

int
krb_create_ticket(KTEXT tkt, unsigned char flags, 
		  char *pname, char *pinstance, char *prealm, 
		  int32_t paddress, void *session, 
		  int16_t life, int32_t time_sec, 
		  char *sname, char *sinstance, des_cblock *key)
{
    des_key_schedule schedule;
    unsigned char *p = tkt->dat;

    memset(tkt, 0, sizeof(KTEXT_ST));

    p += put_int(flags, p, 1);
    p += put_nir(pname, pinstance, prealm, p);
    
    p += put_address(paddress, p);
    
    memcpy(p, session, 8);
    p += 8;

    p += put_int(life, p, 1);
    p += put_int(time_sec, p, 4);

    p += put_nir(sname, sinstance, NULL, p);

    /* multiple of eight bytes */
    tkt->length = (p - tkt->dat + 7) & ~7;

    /* Check length of ticket */
    if (tkt->length > (sizeof(KTEXT_ST) - 7)) {
        memset(tkt->dat, 0, tkt->length);
        tkt->length = 0;
        return KFAILURE /* XXX */;
    }

    encrypt_ktext(tkt, key, DES_ENCRYPT);
    return KSUCCESS;
}
