Implement a program could only be launched by

来源:互联网 发布:基础算法面试题 编辑:程序博客网 时间:2024/06/05 22:39

Purpose

Support a program Callee that could only be launched by Caller; so Callee cannot be launched through shell, or other programs.


Solution Idea

1. caller process passing a string value to callee process, using command line

    callee --id idstring

2. caller pass the MD5 string through stdin

3. callee get idstring from command line option

4. callee regenerate the MD5 string for idstring, saved as str1

5. callee get MD5 string from stdin, and saved in str2

6. callee compare str1 and str2 whether they are same.



Caller:

#!/bin/kshid=hellohash0="$(echo -n "${id}" | md5sum | awk '{print $1}')"./a.out --id ${id} <<EOF$hash0EOF

Callee:

#include <time.h>#include <getopt.h>#include <openssl/md5.h>#include <iostream>static struct option long_options[] = {    {"help",    no_argument,       0, 'h'},     // help    {"id",      required_argument, 0, 'i'},     // id    {0,         0,                 0, 0  }};/** * generate a MD5 hash value for string str. */std::string str2md5(const std::string & str) {    unsigned char digest[16];    char buffer[16 * 2 + 1] = { '\0' };    MD5_CTX c;    MD5_Init(&c);    const char * plain = str.c_str();    int length = str.length();    while (length > 0) {        if (length > 512) {            MD5_Update(&c, plain, 512);        } else {            MD5_Update(&c, plain, length);        }        length -= 512;        plain += 512;    }    MD5_Final(digest, &c);    for (int n = 0; n < 16; ++n) {        snprintf(&(buffer[n*2]), 16*2, "%02x", (unsigned int)digest[n]);    }        //std::cout << "MD5[" << str << "]=[" << buffer << "]" << std::endl;    return buffer;}int main(int argc, char * argv[]) {    std::string id; // input parameter    int c = 0;    while (true) {        int option_index = 0;        c = getopt_long(argc, argv, "hc:j:n:u:", long_options, &option_index);        if (c == -1) {            break;        }        switch (c) {            case 'h':                printf("Usage ...\n");                exit(0);            case 'i':                id = optarg;                break;            default:                printf("Invalid option: %c\n", c);                return false;        }    }    /** read 2 hash value from stdin */    std::string hash0;    std::cin >> hash0;  // read first line     /** regenerate a hash value, based on time and input value */    std::string md5string = str2md5(id);    /** compare the new generated hash value with passing in hash value */    if (md5string == hash0) {        std::cout << "id=[" << id << "] is verified with SUCCESS" << std::endl;    }    else {        std::cout << "id=[" << id << "] is verified with FAILURE" << std::endl;    }    return 0;}

Compile and Execute

$ g++ tt.cpp -lcrypto$ ./caller.ksh id=[hello] is verified with SUCCESS


0 0