Exemplo n.º 1
0
CERTCertificate*
find_certificate(CERTCertDBHandle *handle, const char *name, PRBool ascii)
{
    CERTCertificate *cert = NULL;
    SECItem der;
    PRFileDesc *certFile;

    if (handle == NULL || name == NULL)
        return NULL;

    if (ascii == PR_FALSE) { 
        /* by default need to check if there is cert nick is given */
        cert = CERT_FindCertByNicknameOrEmailAddr (handle, (char *) name);
        if (cert != NULL)
            return cert;
    }

    certFile = PR_Open(name, PR_RDONLY, 0);
    if (certFile == NULL) {
        return NULL;
    }

    if (SECU_ReadDERFromFile(&der, certFile, ascii, PR_FALSE) == SECSuccess) {
        cert = CERT_DecodeCertFromPackage((char*)der.data, der.len);
        SECITEM_FreeItem(&der, PR_FALSE);
    }
    PR_Close(certFile);

    return cert;
}
Exemplo n.º 2
0
NS_IMETHODIMP
nsNSSCertificateDB::FindCertByEmailAddress(nsISupports *aToken, const char *aEmailAddress, nsIX509Cert **_retval)
{
  nsNSSShutDownPreventionLock locker;
  CERTCertificate *any_cert = CERT_FindCertByNicknameOrEmailAddr(CERT_GetDefaultCertDB(), (char*)aEmailAddress);
  if (!any_cert)
    return NS_ERROR_FAILURE;

  CERTCertificateCleaner certCleaner(any_cert);
    
  // any_cert now contains a cert with the right subject, but it might not have the correct usage
  CERTCertList *certlist = CERT_CreateSubjectCertList(
    nsnull, CERT_GetDefaultCertDB(), &any_cert->derSubject, PR_Now(), PR_TRUE);
  if (!certlist)
    return NS_ERROR_FAILURE;  

  CERTCertListCleaner listCleaner(certlist);

  if (SECSuccess != CERT_FilterCertListByUsage(certlist, certUsageEmailRecipient, PR_FALSE))
    return NS_ERROR_FAILURE;
  
  if (CERT_LIST_END(CERT_LIST_HEAD(certlist), certlist))
    return NS_ERROR_FAILURE;
  
  nsNSSCertificate *nssCert = new nsNSSCertificate(CERT_LIST_HEAD(certlist)->cert);
  if (!nssCert)
    return NS_ERROR_OUT_OF_MEMORY;

  NS_ADDREF(nssCert);
  *_retval = static_cast<nsIX509Cert*>(nssCert);
  return NS_OK;
}
Exemplo n.º 3
0
Arquivo: crlutil.c Projeto: ekr/nss
static CERTSignedCrl *
FindCRL(CERTCertDBHandle *certHandle, char *name, int type)
{
    CERTSignedCrl *crl = NULL;
    CERTCertificate *cert = NULL;
    SECItem derName;

    derName.data = NULL;
    derName.len = 0;

    cert = CERT_FindCertByNicknameOrEmailAddr(certHandle, name);
    if (!cert) {
        CERTName *certName = NULL;
        PLArenaPool *arena = NULL;
        SECStatus rv = SECSuccess;

        certName = CERT_AsciiToName(name);
        if (certName) {
            arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
            if (arena) {
                SECItem *nameItem =
                    SEC_ASN1EncodeItem(arena, NULL, (void *)certName,
                                       SEC_ASN1_GET(CERT_NameTemplate));
                if (nameItem) {
                    rv = SECITEM_CopyItem(NULL, &derName, nameItem);
                }
                PORT_FreeArena(arena, PR_FALSE);
            }
            CERT_DestroyName(certName);
        }

        if (rv != SECSuccess) {
            SECU_PrintError(progName, "SECITEM_CopyItem failed, out of memory");
            return ((CERTSignedCrl *)NULL);
        }

        if (!derName.len || !derName.data) {
            SECU_PrintError(progName, "could not find certificate named '%s'", name);
            return ((CERTSignedCrl *)NULL);
        }
    } else {
        SECITEM_CopyItem(NULL, &derName, &cert->derSubject);
        CERT_DestroyCertificate(cert);
    }

    crl = SEC_FindCrlByName(certHandle, &derName, type);
    if (crl == NULL)
        SECU_PrintError(progName, "could not find %s's CRL", name);
    if (derName.data) {
        SECITEM_FreeItem(&derName, PR_FALSE);
    }
    return (crl);
}
Exemplo n.º 4
0
SecIdentityRef CERT_FindIdentityByUsage(SecKeychainRef keychainOrArray,
			 char *nickname, SECCertUsage usage, Boolean validOnly, void *proto_win)
{
    SecIdentityRef identityRef = NULL;
    SecCertificateRef cert = CERT_FindCertByNicknameOrEmailAddr(keychainOrArray, nickname);
    if (!cert)
	return NULL;

    SecIdentityCreateWithCertificate(keychainOrArray, cert, &identityRef);
    CFRelease(cert);

    return identityRef;
}
Exemplo n.º 5
0
CERTCertificate *
getCert(const char *name, PRBool isAscii, const char * progName)
{
    CERTCertificate * cert;
    CERTCertDBHandle *defaultDB;
    PRFileDesc*     fd;
    SECStatus       rv;
    SECItem         item        = {0, NULL, 0};

    defaultDB = CERT_GetDefaultCertDB();

    /* First, let's try to find the cert in existing DB. */
    cert = CERT_FindCertByNicknameOrEmailAddr(defaultDB, name);
    if (cert) {
        return cert;
    }

    /* Don't have a cert with name "name" in the DB. Try to
     * open a file with such name and get the cert from there.*/
    fd = PR_Open(name, PR_RDONLY, 0777); 
    if (!fd) {
	PRIntn err = PR_GetError();
    	fprintf(stderr, "open of %s failed, %d = %s\n", 
	        name, err, SECU_Strerror(err));
	return cert;
    }

    rv = SECU_ReadDERFromFile(&item, fd, isAscii);
    PR_Close(fd);
    if (rv != SECSuccess) {
	fprintf(stderr, "%s: SECU_ReadDERFromFile failed\n", progName);
	return cert;
    }

    if (!item.len) { /* file was empty */
	fprintf(stderr, "cert file %s was empty.\n", name);
	return cert;
    }

    cert = CERT_NewTempCertificate(defaultDB, &item, 
                                   NULL     /* nickname */, 
                                   PR_FALSE /* isPerm */, 
				   PR_TRUE  /* copyDER */);
    if (!cert) {
	PRIntn err = PR_GetError();
	fprintf(stderr, "couldn't import %s, %d = %s\n",
	        name, err, SECU_Strerror(err));
    }
    PORT_Free(item.data);
    return cert;
}
Exemplo n.º 6
0
CERTDistNames *
CERT_DistNamesFromNicknames(CERTCertDBHandle *handle, char **nicknames,
                            int nnames)
{
    CERTDistNames *dnames = NULL;
    PLArenaPool *arena;
    int i, rv;
    SECItem *names = NULL;
    CERTCertificate *cert = NULL;

    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
    if (arena == NULL)
        goto loser;
    dnames = PORT_ArenaZNew(arena, CERTDistNames);
    if (dnames == NULL)
        goto loser;

    dnames->arena = arena;
    dnames->nnames = nnames;
    dnames->names = names = PORT_ArenaZNewArray(arena, SECItem, nnames);
    if (names == NULL)
        goto loser;

    for (i = 0; i < nnames; i++) {
        cert = CERT_FindCertByNicknameOrEmailAddr(handle, nicknames[i]);
        if (cert == NULL)
            goto loser;
        rv = SECITEM_CopyItem(arena, &names[i], &cert->derSubject);
        if (rv == SECFailure)
            goto loser;
        CERT_DestroyCertificate(cert);
    }
    return dnames;

loser:
    if (cert != NULL)
        CERT_DestroyCertificate(cert);
    if (arena != NULL)
        PORT_FreeArena(arena, PR_FALSE);
    return NULL;
}
Exemplo n.º 7
0
FILE *
smime_encrypt(FILE *ip, const char *ignored, const char *to)
{
	NSSCMSMessage	*msg;
	NSSCMSContentInfo	*content;
	NSSCMSEnvelopedData	*data;
	NSSCMSRecipientInfo	*info;
	CERTCertificate	*cert[2];
	CERTCertDBHandle	*handle;
	SECOidTag	tag;
	FILE	*hp, *pp, *yp;
	int	keysize;
	char	*nickname, *vn;
	int	vs;

	if (nss_init() != OKAY)
		return NULL;
	handle = CERT_GetDefaultCertDB();
	vn = ac_alloc(vs = strlen(to) + 30);
	snprintf(vn, vs, "smime-nickname-%s", to);
	nickname = value(vn);
	ac_free(vn);
	if ((cert[0] = CERT_FindCertByNicknameOrEmailAddr(handle,
			nickname ? nickname : (char *)to)) == NULL) {
		if (nickname)
			fprintf(stderr, "Cannot find certificate \"%s\".\n",
					nickname);
		else
			fprintf(stderr, "Cannot find certificate for <%s>.\n",
					to);
		return NULL;
	}
	cert[1] = NULL;
	if (getcipher(to, &tag, &keysize) != OKAY)
		return NULL;
	if ((msg = NSS_CMSMessage_Create(NULL)) == NULL) {
		fprintf(stderr, "Cannot create CMS message.\n");
		return NULL;
	}
	if ((data = NSS_CMSEnvelopedData_Create(msg, tag, keysize)) == NULL) {
		fprintf(stderr, "Cannot create enveloped data.\n");
		return NULL;
	}
	content = NSS_CMSMessage_GetContentInfo(msg);
	if (NSS_CMSContentInfo_SetContent_EnvelopedData(msg, content, data)
			!= SECSuccess) {
		fprintf(stderr, "Cannot attach enveloped data.\n");
		return NULL;
	}
	content = NSS_CMSEnvelopedData_GetContentInfo(data);
	if (NSS_CMSContentInfo_SetContent_Data(msg, content, NULL, PR_FALSE)
			!= SECSuccess) {
		fprintf(stderr, "Cannot attach CMS data.\n");
		return NULL;
	}
	if ((info = NSS_CMSRecipientInfo_Create(msg, cert[0])) == NULL) {
		fprintf(stderr, "Cannot create CMS recipient information.\n");
		return NULL;
	}
	if (NSS_CMSEnvelopedData_AddRecipient(data, info) != SECSuccess) {
		fprintf(stderr, "Cannot add CMS recipient information.\n");
		return NULL;
	}
	CERT_DestroyCertificate(cert[0]);
	if ((yp = encode(ip, &hp, &pp, msg, base64_cb)) == NULL)
		return NULL;
	NSS_CMSMessage_Destroy(msg);
	return smime_encrypt_assemble(hp, yp);
}
Exemplo n.º 8
0
static int
sm_encrypt(CamelCipherContext *context, const char *userid, GPtrArray *recipients, CamelMimePart *ipart, CamelMimePart *opart, CamelException *ex)
{
	struct _CamelSMIMEContextPrivate *p = ((CamelSMIMEContext *)context)->priv;
	/*NSSCMSRecipientInfo **recipient_infos;*/
	CERTCertificate **recipient_certs = NULL;
	NSSCMSContentInfo *cinfo;
	PK11SymKey *bulkkey = NULL;
	SECOidTag bulkalgtag;
	int bulkkeysize, i;
	CK_MECHANISM_TYPE type;
	PK11SlotInfo *slot;
	PLArenaPool *poolp;
	NSSCMSMessage *cmsg = NULL;
	NSSCMSEnvelopedData *envd;
 	NSSCMSEncoderContext *enc = NULL;
	CamelStreamMem *mem;
	CamelStream *ostream = NULL;
	CamelDataWrapper *dw;
	CamelContentType *ct;

	poolp = PORT_NewArena(1024);
	if (poolp == NULL) {
		camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM, g_strerror (ENOMEM));
		return -1;
	}

	/* Lookup all recipients certs, for later working */
	recipient_certs = (CERTCertificate **)PORT_ArenaZAlloc(poolp, sizeof(*recipient_certs[0])*(recipients->len + 1));
	if (recipient_certs == NULL) {
		camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM, g_strerror (ENOMEM));
		goto fail;
	}

	for (i=0;i<recipients->len;i++) {
		recipient_certs[i] = CERT_FindCertByNicknameOrEmailAddr(p->certdb, recipients->pdata[i]);
		if (recipient_certs[i] == NULL) {
			camel_exception_setv(ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot find certificate for `%s'"), recipients->pdata[i]);
			goto fail;
		}
	}

	/* Find a common algorithm, probably 3DES anyway ... */
	if (NSS_SMIMEUtil_FindBulkAlgForRecipients(recipient_certs, &bulkalgtag, &bulkkeysize) != SECSuccess) {
		camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot find common bulk encryption algorithm"));
		goto fail;
	}

	/* Generate a new bulk key based on the common algorithm - expensive */
	type = PK11_AlgtagToMechanism(bulkalgtag);
	slot = PK11_GetBestSlot(type, context);
	if (slot == NULL) {
		/* PORT_GetError(); ?? */
		camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot allocate slot for encryption bulk key"));
		goto fail;
	}

	bulkkey = PK11_KeyGen(slot, type, NULL, bulkkeysize/8, context);
	PK11_FreeSlot(slot);

	/* Now we can start building the message */
	/* msg->envelopedData->data */
	cmsg = NSS_CMSMessage_Create(NULL);
	if (cmsg == NULL) {
		camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot create CMS Message"));
		goto fail;
	}

	envd = NSS_CMSEnvelopedData_Create(cmsg, bulkalgtag, bulkkeysize);
	if (envd == NULL) {
		camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot create CMS Enveloped data"));
		goto fail;
	}

	cinfo = NSS_CMSMessage_GetContentInfo(cmsg);
	if (NSS_CMSContentInfo_SetContent_EnvelopedData(cmsg, cinfo, envd) != SECSuccess) {
		camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot attach CMS Enveloped data"));
		goto fail;
	}

	cinfo = NSS_CMSEnvelopedData_GetContentInfo(envd);
	if (NSS_CMSContentInfo_SetContent_Data(cmsg, cinfo, NULL, PR_FALSE) != SECSuccess) {
		camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot attach CMS data object"));
		goto fail;
	}

	/* add recipient certs */
	for (i=0;recipient_certs[i];i++) {
		NSSCMSRecipientInfo *ri = NSS_CMSRecipientInfo_Create(cmsg, recipient_certs[i]);

		if (ri == NULL) {
			camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot create CMS Recipient information"));
			goto fail;
		}

		if (NSS_CMSEnvelopedData_AddRecipient(envd, ri) != SECSuccess) {
			camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot add CMS Recipient information"));
			goto fail;
		}
	}

	/* dump it out */
	ostream = camel_stream_mem_new();
	enc = NSS_CMSEncoder_Start(cmsg,
				   sm_write_stream, ostream,
				   NULL, NULL,
				   NULL, NULL,
				   sm_decrypt_key, bulkkey,
				   NULL, NULL);
	if (enc == NULL) {
		camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot create encoder context"));
		goto fail;
	}

	/* FIXME: Stream the input */
	/* FIXME: Canonicalise the input? */
	mem = (CamelStreamMem *)camel_stream_mem_new();
	camel_data_wrapper_write_to_stream((CamelDataWrapper *)ipart, (CamelStream *)mem);
	if (NSS_CMSEncoder_Update(enc, (char *) mem->buffer->data, mem->buffer->len) != SECSuccess) {
		NSS_CMSEncoder_Cancel(enc);
		camel_object_unref(mem);
		camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM, _("Failed to add data to encoder"));
		goto fail;
	}
	camel_object_unref(mem);

	if (NSS_CMSEncoder_Finish(enc) != SECSuccess) {
		camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM, _("Failed to encode data"));
		goto fail;
	}

	PK11_FreeSymKey(bulkkey);
	NSS_CMSMessage_Destroy(cmsg);
	for (i=0;recipient_certs[i];i++)
		CERT_DestroyCertificate(recipient_certs[i]);
	PORT_FreeArena(poolp, PR_FALSE);

	dw = camel_data_wrapper_new();
	camel_data_wrapper_construct_from_stream(dw, ostream);
	camel_object_unref(ostream);
	dw->encoding = CAMEL_TRANSFER_ENCODING_BINARY;

	ct = camel_content_type_new("application", "x-pkcs7-mime");
	camel_content_type_set_param(ct, "name", "smime.p7m");
	camel_content_type_set_param(ct, "smime-type", "enveloped-data");
	camel_data_wrapper_set_mime_type_field(dw, ct);
	camel_content_type_unref(ct);

	camel_medium_set_content_object((CamelMedium *)opart, dw);
	camel_object_unref(dw);

	camel_mime_part_set_disposition(opart, "attachment");
	camel_mime_part_set_filename(opart, "smime.p7m");
	camel_mime_part_set_description(opart, "S/MIME Encrypted Message");
	camel_mime_part_set_encoding(opart, CAMEL_TRANSFER_ENCODING_BASE64);

	return 0;

fail:
	if (ostream)
		camel_object_unref(ostream);
	if (cmsg)
		NSS_CMSMessage_Destroy(cmsg);
	if (bulkkey)
		PK11_FreeSymKey(bulkkey);

	if (recipient_certs) {
		for (i=0;recipient_certs[i];i++)
			CERT_DestroyCertificate(recipient_certs[i]);
	}

	PORT_FreeArena(poolp, PR_FALSE);

	return -1;
}
Exemplo n.º 9
0
int FileCertExport_main(int argc, char * argv[])
{
    CERTCertListNode *node;
    
    SECStatus rv = 0;
    
    /*初始化数据库*/
    rv = NSS_InitReadWrite(GetSystemDBDir());
    
    
    if (SECSuccess != rv) {
        printf("初始化数据库失败\n");
        
        return -1;
    }
    
    CERTCertList * certs = NULL;
    
    
    CERTCertDBHandle *certHandle;
    
    certHandle = CERT_GetDefaultCertDB();
    
    CERTCertificate *the_cert;
    /*用nickname查找数据库证书*/
    
    char * nickname = "BCDEF";/*nickname*/
    
    the_cert = CERT_FindCertByNicknameOrEmailAddr(certHandle, nickname);
    
    if (NULL == the_cert) {
        printf("nickname为%s证书未找到",nickname);
    }
    
    
    certs = CERT_CreateSubjectCertList(NULL, certHandle, &the_cert->derSubject,
                                       PR_Now(), PR_FALSE);
    
    /*导出cert的文件名称*/
    char * tempCertPath = malloc(255);
    
    memset(tempCertPath, 0, 255);
    strcpy(tempCertPath, GetSystemDBDir());
    
    strcat(tempCertPath, "11111out_2.cer");
    
    FILE * fileOUT = fopen(tempCertPath, "w+b");
    
    if (NULL == fileOUT) {
        printf("%s文件打开失败\n",tempCertPath);
        
        return -1;
    }
    
	CERT_DestroyCertificate(the_cert);
	if (!certs) {
	    return SECFailure;
	}
	for (node = CERT_LIST_HEAD(certs); !CERT_LIST_END(node,certs);
         node = CERT_LIST_NEXT(node)) {
	    the_cert = node->cert;
	    /* now get the subjectList that matches this cert */
        SECItem data;
        

        
	    data.data = the_cert->derCert.data;
	    data.len = the_cert->derCert.len;
	    {
            PRInt32 numBytes = fwrite(data.data,data.len,1,fileOUT);
            if (numBytes != (PRInt32) data.len) {
                rv = SECFailure;
            }
            rv = SECSuccess;
	    } 
	    if (rv != SECSuccess) {
            break;
	    }
	}
    
    fclose(fileOUT);
    
    printf("Export Cert SUCCESS!\n");
    
    if (certs) {
        CERT_DestroyCertList(certs);
    }
    
    rv = NSS_Shutdown();
    
    return rv;
}
Exemplo n.º 10
0
int FileSSLDoublePoint_main(char * strUserPin, char * strNickName)
{
#if 1
    int isServer = 0;
    
    SECStatus rv = SECSuccess;
    
    
    char * buffer = malloc(1024 * 1024);
    
    
    PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
    
    PK11_SetPasswordFunc(GetModulePassword);
    rv = NSS_Initialize(GetSystemDBDir(),
                        "", "",
                        "secmod.db", 0);
    
    
    rv = SSL_OptionSetDefault(SSL_SECURITY, PR_TRUE);
    rv = SSL_OptionSetDefault(SSL_SOCKS, PR_TRUE);
    rv = SSL_OptionSetDefault(SSL_ENABLE_SSL2, PR_TRUE);
    rv = SSL_OptionSetDefault(SSL_ENABLE_SSL3, PR_TRUE);
    rv = SSL_OptionSetDefault(SSL_ENABLE_FDX, PR_TRUE);
    
    rv = SSL_OptionSetDefault(SSL_ENABLE_TLS, PR_TRUE);
    
    rv = NSS_SetDomesticPolicy();
    rv = NSS_SetExportPolicy();
    rv = NSS_SetFrancePolicy();
    //    rv = SSL_CipherPolicySet();
    
    
    
    SSL_ClearSessionCache();
    
    rv = SSL_ConfigServerSessionIDCache(10, 30 , 30, ".");
    
    
    PRFileDesc * tcp_socket = PR_NewTCPSocket();
    
    PRFileDesc * ssl_socket = SSL_ImportFD(NULL,tcp_socket);
    
    if (isServer) {
        
        CERTCertDBHandle *certHandle;
        
        certHandle = CERT_GetDefaultCertDB();
        
        char * nickname = "4914afeedee988071490b98f1120ddac_e73f20c7-176d-4342-ac89-ea7c00bb570a";/*nickname*/
        
        CERTCertificate* cert = NULL;
        cert = CERT_FindCertByNicknameOrEmailAddr(certHandle, nickname);
        
        
        SECKEYPrivateKey *prvKey = NULL;
        
        prvKey = PK11_FindKeyByAnyCert(cert, NULL);
        
        rv = SSL_ConfigSecureServer(ssl_socket, cert,prvKey,ssl_kea_rsa);
        
        
        PRNetAddr netAddr;
        
        PRNetAddr netAddrLocal;
        
        
        rv = PR_InitializeNetAddr(0, 8888, &netAddr);
        
        
        rv = PR_StringToNetAddr("127.0.0.1", &netAddrLocal);
        
        rv = PR_Bind(tcp_socket,&netAddr);
        rv = PR_Listen(tcp_socket, 100);
        
        
        while (1) {
            PRFileDesc * client = PR_Accept(tcp_socket, &netAddr, 6000000);
            PRNetAddr addr;
            
            
            rv = PR_GetSockName(client, &addr);
            
            rv = SSL_ForceHandshake(client);
            
            
            rv = PR_Write(client,"123", 4);
            
            sleep(1);
        }
        
    }
    else
    {
        rv = SSL_AuthCertificateHook(ssl_socket, OwnAuthCertHandler, NULL);
        char * nickname = "nickname";/*nickname*/
        
        rv = SSL_SetURL(ssl_socket, "192.168.18.22");
        
        char * str = malloc(1024) ;

		memset(str, 0, 1024);
        
        strcpy(str ,"GET /test/test2.html HTTP/1.1\r\n");//注意\r\n为回车换行
        //        str = [str stringByAppendingString:@"Accept-Language: zh-cn\r\n"];
        //        str = [str stringByAppendingString:@"Connection: Keep-Alive\r\n"];
        //str = [str stringByAppendingString:@"Host: 192.168.0.106\r\n"];
        strcat(str ,"Host: 192.168.18.22:8443\r\n");
        //        str = [str stringByAppendingString:@"Content-Length: 0\r\n"];
        strcat(str ,"\r\n");
        //        str = [str stringByAppendingString:@"userName=liqiangqiang&password=new_andy\r\n"];
        //        str = [str stringByAppendingString:@"\r\n"];
        
        PRNetAddr netAddr;
        
        
        rv = PR_StringToNetAddr("192.168.18.22", &netAddr);
        
        rv = PR_InitializeNetAddr(0, 8443, &netAddr);
        
        //        rv = PR_GetHostByName();
        //        PR_EnumerateHostEnt
        
        
        rv = PR_Connect(tcp_socket,&netAddr, 300000);

		FILE_LOG_NUMBER("/sdcard/ssl.log", rv);

        rv = SSL_GetClientAuthDataHook(ssl_socket,NSS_GetClientAuthData,strNickName);

		FILE_LOG_NUMBER("/sdcard/ssl.log", rv);
        
        rv = SSL_ForceHandshake(ssl_socket);
        
		FILE_LOG_NUMBER("/sdcard/ssl.log", rv);
        
        rv = PR_Write(tcp_socket, str, strlen(str));
        
		FILE_LOG_NUMBER("/sdcard/ssl.log", rv);

        rv = PR_Read(tcp_socket,buffer, 1024 * 1024);

		FILE_LOG_NUMBER("/sdcard/ssl.log", rv);
        
        FILE * file = fopen("/sdcard/ssl_read.txt", "wb");
        
        //fwrite(buffer, 1, rv, file);

        //rv = PR_Read(tcp_socket,buffer, 1024 * 1024);
        
        fwrite(buffer, 1, rv, file);
        
        fclose(file);
        
        sleep(1);
        
        
        rv = SSL_InvalidateSession(ssl_socket);
        
        rv = PR_Shutdown(tcp_socket, PR_SHUTDOWN_BOTH);
        
        rv = PR_Close(tcp_socket);
        
        rv = ssl_FreeSessionCacheLocks();
        
        rv = NSS_Shutdown();
        
    }
#endif
    
    return 0;
}
Exemplo n.º 11
0
int FileSSL_main(int argc, char * argv[])
{
    bool isServer = true;
    
    SECStatus rv = SECSuccess;

    
    char buffer[32] = {0};
    

    PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
    
    PK11_SetPasswordFunc(GetModulePassword);
    rv = NSS_Initialize(GetSystemDBDir(),
                        "", "",
                        "secmod.db", 0);
    
    
    rv = SSL_OptionSetDefault(SSL_SECURITY, PR_TRUE);
    rv = SSL_OptionSetDefault(SSL_SOCKS, PR_TRUE);
    rv = SSL_OptionSetDefault(SSL_ENABLE_SSL2, PR_TRUE);
    rv = SSL_OptionSetDefault(SSL_ENABLE_SSL3, PR_TRUE);
    rv = SSL_OptionSetDefault(SSL_ENABLE_FDX, PR_TRUE);
    
    rv = SSL_OptionSetDefault(SSL_ENABLE_TLS, PR_TRUE);
    
    rv = NSS_SetDomesticPolicy();
    rv = NSS_SetExportPolicy();
    rv = NSS_SetFrancePolicy();
    //    rv = SSL_CipherPolicySet();
    
    
    
    SSL_ClearSessionCache();
    
    rv = SSL_ConfigServerSessionIDCache(10, 30 , 30, ".");
    
    
    PRFileDesc * socket = PR_NewTCPSocket();
    
    socket = SSL_ImportFD(NULL,socket);
    
    
    
    if (isServer) {
        
        CERTCertDBHandle *certHandle;
        
        certHandle = CERT_GetDefaultCertDB();
        
        char * nickname = "itrus Certificate DB:2013-11-15 12:44:10";/*nickname*/
        
        CERTCertificate* cert = NULL;
        cert = CERT_FindCertByNicknameOrEmailAddr(certHandle, nickname);
        
        
        SECKEYPrivateKey *prvKey = NULL;
        
        prvKey = PK11_FindKeyByAnyCert(cert, NULL);
        
        rv = SSL_ConfigSecureServer(socket, cert,prvKey,ssl_kea_rsa);
        
        
        PRNetAddr netAddr;
        
        PRNetAddr netAddrLocal;
        
        
        rv = PR_InitializeNetAddr(0, 8888, &netAddr);
        
        
        rv = PR_StringToNetAddr("127.0.0.1", &netAddrLocal);
        
        rv = PR_Bind(socket,&netAddr);
        rv = PR_Listen(socket, 100);
        
        
        while (1) {
            PRFileDesc * client = PR_Accept(socket, &netAddr, 6000000);
            PRNetAddr addr;
            
            
            rv = PR_GetSockName(client, &addr);
            
            rv = SSL_ForceHandshake(client);
            
            
            rv = PR_Write(client,"123", 4);
            
            sleep(1);
        }
        
    }
    else
    {
        rv = SSL_SetURL(socket, "127.0.0.1");
        
        PRNetAddr netAddr;
        
        PRNetAddr netAddrLocal;
        
        
        rv = PR_InitializeNetAddr(0, 8888, &netAddr);
        
        
        rv = PR_StringToNetAddr("127.0.0.1", &netAddrLocal);
        
        //        rv = PR_GetHostByName();
        //        PR_EnumerateHostEnt
        rv = PR_Connect(socket,&netAddr, 300000);
        
        rv = SSL_AuthCertificateHook(socket, OwnAuthCertHandler, NULL);
        
        rv = SSL_ForceHandshake(socket);
        
        while (1) {
            rv = PR_Read(socket,buffer, 32);
            
            sleep(1);
        }
        
    }
    
    
    return 0;
}