summaryrefslogtreecommitdiff
path: root/src/commission_func.cc
blob: 21c5d168abb8a492a7f10294c4ee8441dbc62468 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
#include "commission_func.h"

int begin_fcgi() {

    // Set up commissioning enviornment variables.

    bool parseJson, is_err, commissioning = false, complete = false;
    int popen_ret, atmpt_cntr = 0;
    Json::Reader reader;
    Json::Value j_post;
    Json::StyledWriter swriter;
    std::string posted, parse_cmd, parse_logger;
    std::string aasid = "";
    std::string tmp_usrname = "";
    std::string tmp_pass = "";
    std::streambuf * cin_streambuf = std::cin.rdbuf();
    std::streambuf * cout_streambuf = std::cout.rdbuf();
    std::streambuf * cerr_streambuf = std::cerr.rdbuf();
    FILE *fpopen;
    char fileread[MAX_GET];

    //set up the syslog event
    openlog("commissioning.fcgi", LOG_PID | LOG_PERROR, LOG_LOCAL0);

    //set up fcgi environment
    FCGX_Request request;

    FCGX_Init();
    FCGX_InitRequest(&request, 0, 0);

    //listen for requests
    while (FCGX_Accept_r(&request) == 0 && !complete) {

        // set streambuffers to fcgi request
        fcgi_streambuf cin_fcgi_streambuf(request.in);
        fcgi_streambuf cout_fcgi_streambuf(request.out);
        fcgi_streambuf cerr_fcgi_streambuf(request.err);

        std::cin.rdbuf(&cin_fcgi_streambuf);
        std::cout.rdbuf(&cout_fcgi_streambuf);
        std::cerr.rdbuf(&cerr_fcgi_streambuf);


        // receive data from POST
        posted = get_request_content(request);


        if (posted.length() == 0) {
            //standard output (check if commissioning is on)
            std::cout << confirmCommissioning();
        } else {
            //receive POSTed Json data
            bool parseJson = reader.parse(posted, j_post);

            //error state
            if (!parseJson) {
                syslog (LOG_ALERT, "Received unparsible data");
                std::cout << ERROR_PARSE;
                std::cout << "Content-type: text/plain"
                << "\r\n"
                << "Output : "
                << posted 
                <<"\r\n";

            //if sent data doesn't follow proper formatting
            } else if (!properInput(j_post)) {
                std::cout << printMsg(commissioning, atmpt_cntr, tmp_pass, true, aasid, ERR_MALDATA, AASTYPE_ERR);
                syslog (LOG_ALERT, "Received malformed user data entry");

            //if we are not in the middle of a commissioning session
            } else if (!commissioning) {

                //if the user requests an illegal username
                if(!legalName(j_post["username"].asString())) {
                    std::cout << printMsg(commissioning, atmpt_cntr, tmp_pass, true, aasid, ERR_ILLEGALUSRNAME, AASTYPE_ERR);
                    syslog (LOG_ALERT, "Received request for unauthorized username");

                } else {

                    // start a new commissioning session
                    commissioning = true;
                    atmpt_cntr = 0;
                    tmp_usrname = j_post["username"].asString();
                    aasid = gen_aasid();

                    //send confirmation message
                    std::cout << printMsg(commissioning, atmpt_cntr, tmp_pass, false, aasid, MSG_NEWPASSWD, AASTYPE_QSTN);
                    parse_cmd = "Received username: " + tmp_usrname + ", awaiting password request";
                    syslog (LOG_ALERT, parse_cmd.c_str());
                }
            // we're in a commissioning session           
            } else {
                if(tmp_pass == "") {
                    //password request
                    if(j_post["aasAnswer"].asString() == "") {
                        //password was omitted
                        std::cout << printMsg(commissioning, atmpt_cntr, tmp_pass, true, aasid, ERR_NOPASS, AASTYPE_ERR);
                        parse_cmd = tmp_usrname + " password omission";
                        syslog (LOG_ALERT, parse_cmd.c_str());

                    }else if (j_post["aasID"] != aasid) {
                        //aasID mismatch
                        std::cout << printMsg(commissioning, atmpt_cntr, tmp_pass, true, aasid, ERR_BADAASID, AASTYPE_ERR);
                        parse_cmd = tmp_usrname + " aasid does not match";
                        syslog (LOG_ALERT, parse_cmd.c_str());
                    } else if (j_post["username"].asString() != tmp_usrname) {
                        //user ID mismatch
                        std::cout << printMsg(commissioning, atmpt_cntr, tmp_pass, true, aasid, ERR_USRMISMATCH, AASTYPE_ERR);
                        parse_cmd = tmp_usrname + " returned a mismatched username mid session";
                        syslog (LOG_ALERT, parse_cmd.c_str());
                    } else {
                        //successful password request
                        atmpt_cntr = 0;
                        tmp_pass = j_post["aasAnswer"].asString();
                        std::cout << printMsg(commissioning, atmpt_cntr, tmp_pass, false, aasid, MSG_RETYPEPASS, AASTYPE_QSTN);
                        parse_cmd = tmp_usrname + " successfuly requested a password. Awaiting verification";
                        syslog (LOG_ALERT, parse_cmd.c_str());
                    }
                } else {
                    //password request
                    if(j_post["aasAnswer"].asString() == "") {
                        //password was omitted
                        std::cout << printMsg(commissioning, atmpt_cntr, tmp_pass, true, aasid, ERR_NOPASS, AASTYPE_ERR);
                        parse_cmd = tmp_usrname + " password omission";

                    }else if (j_post["aasID"] != aasid) {
                        //aasID mismatch
                        std::cout << printMsg(commissioning, atmpt_cntr, tmp_pass, true, aasid, ERR_BADAASID, AASTYPE_ERR);
                        parse_cmd = tmp_usrname + " aasid does not match";
                        syslog (LOG_ALERT, parse_cmd.c_str());

                    } else if (j_post["username"].asString() != tmp_usrname) {
                        //user ID mismatch
                        std::cout << printMsg(commissioning, atmpt_cntr, tmp_pass, true, aasid, ERR_USRMISMATCH, AASTYPE_ERR);
                        parse_cmd = tmp_usrname + " returned a mismatched username mid session";
                        syslog (LOG_ALERT, parse_cmd.c_str());

                    } else if (j_post["aasAnswer"].asString() != tmp_pass) {
                        std::cout << printMsg(commissioning, atmpt_cntr, tmp_pass, true, aasid, ERR_PWMISMATCH, AASTYPE_ERR);
                        parse_cmd = tmp_usrname + " verification attempt did not match";
                        syslog (LOG_ALERT, parse_cmd.c_str());

                    } else {
                        //successful password request
                        atmpt_cntr = 0;
                        commissioning = false;
                        std::cout << printMsg(commissioning, atmpt_cntr, tmp_pass, false, aasid, MSG_SUCCESS, AASTYPE_INFO);
                        parse_cmd = tmp_usrname + " data entry successful. Creating user account";
                        syslog (LOG_ALERT, parse_cmd.c_str());

                        /******
                         *  COMMISSIONING CODE
                         * ***/

                        /****useradd****/
                        fpopen = popen(useradd_cmd_gen(tmp_usrname).c_str(), "r");
                        if (fpopen == NULL) {
                            syslog (LOG_ALERT, "popen for useradd failed to return a useful pointer");
                            //handle error via logging, closing
                        }

                        while (fgets(fileread, MAX_GET, fpopen) != NULL) {
                            printf("%s", fileread);
                        }
                        popen_ret = pclose(fpopen);
                        if (popen_ret == -1) {
                            syslog (LOG_ALERT, "pclose for useradd failed");
                            //handle error via logging, closing
                        }

                        /****passwd****/
                        fpopen = popen(passwd_cmd_gen(tmp_usrname).c_str(), "w");
                        if (fpopen == NULL) {
                            syslog (LOG_ALERT, "popen for passwd failed to return a useful pointer");
                            //handle error via logging, closing                           
                        }
                        fprintf(fpopen, "%s\n", tmp_pass.c_str());
                        fprintf(fpopen, "%s\n", tmp_pass.c_str());
                        popen_ret = pclose(fpopen);
                        if (popen_ret == -1) {
                            syslog (LOG_ALERT, "pclose for passwd failed");
                            // handle error via logging, closing
                        }

                        /****mts-ubpasswd****/
                        fpopen = popen(POPEN_MTS_UBPW.c_str(), "w");
                        if (fpopen == NULL) {
                            syslog (LOG_ALERT, "mts-ubpasswd for passwd failed to return a useful pointer");
                            //handle error via logging, closing
                        }
                        fputs(tmp_pass.c_str(), fpopen);
                        popen_ret = pclose(fpopen);
                        if (popen_ret == -1) {
                            syslog (LOG_ALERT, "pclose for mts-ubpasswd failed");
                            //handle error via logging, closing
                        }
                        /*****
                         *   EMPTY TEMP VALS
                         * ***
                         * 

                        /******
                         *   CLOSEOUTCODE
                         * ****/
                        fpopen = popen(POPEN_CLOSEALL.c_str(), "r");
                        if (fpopen == NULL) {
                            syslog (LOG_ALERT, "closeall routine failed to return a useful pointer");
                            //handle error via logging, closing
                        } 

                        while (fgets(fileread, MAX_GET, fpopen) != NULL) {
                            printf("%s", fileread);
                        }
                        popen_ret = pclose(fpopen);
                        if (popen_ret == -1) {
                            syslog (LOG_ALERT, "pclose for closeall routine failed ");
                            //handle error via logging, closing
                        }
                        complete = true;
                    }
                }
            }
        }
    }

    // restore stdio streambufs
    std::cin.rdbuf(cin_streambuf);
    std::cout.rdbuf(cout_streambuf);
    std::cerr.rdbuf(cerr_streambuf);

    return 0;
}

/*****message delivery function definitions ********************************************/

std::string confirmCommissioning() {
    std::string formatted_output;
    Json::Value output;
    Json::StyledWriter writer;

    output["code"] = 200;
    output["status"] = "success";

    formatted_output = HEADER + writer.write(output) + "\n";

    return formatted_output;
}

std::string printMsg(bool &is_commission, int &atmpt_cntr, std::string &pw, bool is_err, std::string aasid, std::string msg, std::string aastype) {
    std::string formatted_output, msg_output;
    Json::Value output;
    Json::StyledWriter writer;
    bool aasDone = false;
    int retries_left;

    //set aasDone
    if (aastype == MSG_SUCCESS) {
        aasDone = true;
    }

   //not commissioning yet. 
    msg_output = msg;
    if (is_err) {
        msg_output += ": Please try again.";

        //mid commission attempt.
        if (is_commission) {
            atmpt_cntr++;
            retries_left = NUM_ATTEMPTS - atmpt_cntr;
            msg_output = msg + ": Retries left: " + std::to_string(retries_left);

            //commission attempts exhausted.
            if (retries_left <= 0) {
                atmpt_cntr = 0;
                is_commission = false;
                pw = "";
                msg_output += ". Attempts exhausted. Please reattempt username.";
            }
        }
    }

    output["code"] = 200;
    output["result"]["aasDone"] = aasDone;
    output["result"]["aasID"] = aasid;
    output["result"]["aasMsg"] = msg_output;
    output["result"]["aasType"] = aastype;
    output["status"] = "success";

    return HEADER + writer.write(output) + "\n";
}


/******** recieve input function definitions *********************************/
std::string get_request_content(const FCGX_Request &request) {
    char * content_length_str = FCGX_GetParam("CONTENT_LENGTH", request.envp);
    unsigned long content_length = STDIN_MAX;

    if (content_length_str) {
        content_length = strtol(content_length_str, &content_length_str, 10);
        if (*content_length_str) {
            std::cerr << "Can't Parse 'CONTENT_LENGTH='"
                 << FCGX_GetParam("CONTENT_LENGTH", request.envp)
                 << "'. Consuming stdin up to " << STDIN_MAX << std::endl;
        }

        if (content_length > STDIN_MAX) {
            content_length = STDIN_MAX;
        }
    } else {
        // Do not read from stdin if CONTENT_LENGTH is missing
        content_length = 0;
    }

    char * content_buffer = new char[content_length];
    std::cin.read(content_buffer, content_length);
    content_length = std::cin.gcount();

    // Chew up any remaining stdin - this shouldn't be necessary
    // but is because mod_fastcgi doesn't handle it correctly.

    // ignore() doesn't set the eof bit in some versions of glibc++
    // so use gcount() instead of eof()...
    do std::cin.ignore(1024); while (std::cin.gcount() == 1024);

    std::string content(content_buffer, content_length);
    delete [] content_buffer;
    return content;
}

std::string gen_aasid() {
    std::string output;
    std::string table = "ABCDEFGHIJKLMNOPQRSTUVWZYZ1234567890";
    
srand(time(0));
    for (int i=0; i<AASID_LENGTH; i++) {
        output += table[rand() % (table.length()-1)];
    }
    return output;
}

bool properInput(Json::Value jobj) {
    bool aasid = false;
    bool aasanswr = false;
    bool usrname = false;
    std::vector<std::string> memberNames;
    std::string m_username = "username";
    std::string m_aasid = "aasID";
    std::string m_aasAnswr = "aasAnswer";

    memberNames = jobj.getMemberNames();

    for (int i=0; i < memberNames.size(); i++) {
        if (memberNames[i] == m_username) {
            usrname = true;
        } else if (memberNames[i] == m_aasid) {
            aasid = true;
        } else if (memberNames[i] == m_aasAnswr) {
            aasanswr = true;
        }
    }
    if (aasid && aasanswr && usrname) {
        return true;
    }
    return false;
}
/* TODO: expand list of legal and illegal names as needed */
bool legalName(std::string name) {
    /*
    std::string cmd = "/usr/bin/id -u \"";
    char *temp = NULL;
    std::string popen_out;
    */
    if (name != "root") {
        syslog (LOG_ALERT, "Received a legal name request");
        //the name is available
        return true;
    }
    syslog (LOG_ALERT, "Receives an illegal name request");
    return false;
}

/*** generate command functions ***/
std::string passwd_cmd_gen(std::string pw) {
    std::string cmd = "/usr/bin/passwd \"";
    cmd +=pw;
    cmd +="\"";
    return cmd;
}

std::string useradd_cmd_gen(std::string usr) {
    std::string cmd = "/usr/sbin/useradd -U -m -G sudo,dialout,disk -s /bin/bash -- \"";
    cmd +=usr;
    cmd +="\"";
    return cmd;
}