1 /*
2  * rtpw.c
3  *
4  * rtp word sender/receiver
5  *
6  * David A. McGrew
7  * Cisco Systems, Inc.
8  *
9  * This app is a simple RTP application intended only for testing
10  * libsrtp.  It reads one word at a time from words.txt (or
11  * whatever file is specified as DICT_FILE or with -w), and sends one word out
12  * each USEC_RATE microseconds.  Secure RTP protections can be
13  * applied.  See the usage() function for more details.
14  *
15  */
16 
17 /*
18  *
19  * Copyright (c) 2001-2017, Cisco Systems, Inc.
20  * All rights reserved.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  *
26  *   Redistributions of source code must retain the above copyright
27  *   notice, this list of conditions and the following disclaimer.
28  *
29  *   Redistributions in binary form must reproduce the above
30  *   copyright notice, this list of conditions and the following
31  *   disclaimer in the documentation and/or other materials provided
32  *   with the distribution.
33  *
34  *   Neither the name of the Cisco Systems, Inc. nor the names of its
35  *   contributors may be used to endorse or promote products derived
36  *   from this software without specific prior written permission.
37  *
38  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
39  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
40  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
41  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
42  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
43  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
44  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
45  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
46  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
47  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
49  * OF THE POSSIBILITY OF SUCH DAMAGE.
50  *
51  */
52 
53 #ifdef HAVE_CONFIG_H
54 #include <config.h>
55 #endif
56 
57 #include "getopt_s.h" /* for local getopt()  */
58 
59 #include <stdio.h>  /* for printf, fprintf */
60 #include <stdlib.h> /* for atoi()          */
61 #include <errno.h>
62 #include <signal.h> /* for signal()        */
63 
64 #include <string.h> /* for strncpy()       */
65 #include <time.h>   /* for usleep()        */
66 
67 #ifdef HAVE_UNISTD_H
68 #include <unistd.h> /* for close()         */
69 #elif defined(_MSC_VER)
70 #include <io.h> /* for _close()        */
71 #define close _close
72 #endif
73 #ifdef HAVE_SYS_SOCKET_H
74 #include <sys/socket.h>
75 #endif
76 #ifdef HAVE_NETINET_IN_H
77 #include <netinet/in.h>
78 #elif defined HAVE_WINSOCK2_H
79 #include <winsock2.h>
80 #include <ws2tcpip.h>
81 #define RTPW_USE_WINSOCK2 1
82 #endif
83 #ifdef HAVE_ARPA_INET_H
84 #include <arpa/inet.h>
85 #endif
86 
87 #include "srtp.h"
88 #include "rtp.h"
89 #include "util.h"
90 
91 #define DICT_FILE "words.txt"
92 #define USEC_RATE (5e5)
93 #define MAX_WORD_LEN 128
94 #define ADDR_IS_MULTICAST(a) IN_MULTICAST(htonl(a))
95 #define MAX_KEY_LEN 96
96 
97 #ifndef HAVE_USLEEP
98 #ifdef HAVE_WINDOWS_H
99 #define usleep(us) Sleep((us) / 1000)
100 #else
101 #define usleep(us) sleep((us) / 1000000)
102 #endif
103 #endif
104 
105 /*
106  * the function usage() prints an error message describing how this
107  * program should be called, then calls exit()
108  */
109 
110 void usage(char *prog_name);
111 
112 /*
113  * leave_group(...) de-registers from a multicast group
114  */
115 
116 void leave_group(int sock, struct ip_mreq mreq, char *name);
117 
118 /*
119  * setup_signal_handler() sets up a signal handler to trigger
120  * cleanups after an interrupt
121  */
122 int setup_signal_handler(char *name);
123 
124 /*
125  * handle_signal(...) handles interrupt signal to trigger cleanups
126  */
127 
128 volatile int interrupted = 0;
129 
130 /*
131  * program_type distinguishes the [s]rtp sender and receiver cases
132  */
133 
134 typedef enum { sender, receiver, unknown } program_type;
135 
main(int argc,char * argv[])136 int main(int argc, char *argv[])
137 {
138     char *dictfile = DICT_FILE;
139     FILE *dict;
140     char word[MAX_WORD_LEN];
141     int sock, ret;
142     struct in_addr rcvr_addr;
143     struct sockaddr_in name;
144     struct ip_mreq mreq;
145 #if BEW
146     struct sockaddr_in local;
147 #endif
148     program_type prog_type = unknown;
149     srtp_sec_serv_t sec_servs = sec_serv_none;
150     unsigned char ttl = 5;
151     int c;
152     int key_size = 128;
153     int tag_size = 8;
154     int gcm_on = 0;
155     char *input_key = NULL;
156     int b64_input = 0;
157     char *address = NULL;
158     char key[MAX_KEY_LEN];
159     unsigned short port = 0;
160     rtp_sender_t snd;
161     srtp_policy_t policy;
162     srtp_err_status_t status;
163     int len;
164     int expected_len;
165     int do_list_mods = 0;
166     uint32_t ssrc = 0xdeadbeef; /* ssrc value hardcoded for now */
167 #ifdef RTPW_USE_WINSOCK2
168     WORD wVersionRequested = MAKEWORD(2, 0);
169     WSADATA wsaData;
170 
171     ret = WSAStartup(wVersionRequested, &wsaData);
172     if (ret != 0) {
173         fprintf(stderr, "error: WSAStartup() failed: %d\n", ret);
174         exit(1);
175     }
176 #endif
177 
178     memset(&policy, 0x0, sizeof(srtp_policy_t));
179 
180     printf("Using %s [0x%x]\n", srtp_get_version_string(), srtp_get_version());
181 
182     if (setup_signal_handler(argv[0]) != 0) {
183         exit(1);
184     }
185 
186     /* initialize srtp library */
187     status = srtp_init();
188     if (status) {
189         printf("error: srtp initialization failed with error code %d\n",
190                status);
191         exit(1);
192     }
193 
194     /* check args */
195     while (1) {
196         c = getopt_s(argc, argv, "b:k:rsgt:ae:ld:w:");
197         if (c == -1) {
198             break;
199         }
200         switch (c) {
201         case 'b':
202             b64_input = 1;
203         /* fall thru */
204         case 'k':
205             input_key = optarg_s;
206             break;
207         case 'e':
208             key_size = atoi(optarg_s);
209             if (key_size != 128 && key_size != 256) {
210                 printf("error: encryption key size must be 128 or 256 (%d)\n",
211                        key_size);
212                 exit(1);
213             }
214             sec_servs |= sec_serv_conf;
215             break;
216         case 't':
217             tag_size = atoi(optarg_s);
218             if (tag_size != 8 && tag_size != 16) {
219                 printf("error: GCM tag size must be 8 or 16 (%d)\n", tag_size);
220                 exit(1);
221             }
222             break;
223         case 'a':
224             sec_servs |= sec_serv_auth;
225             break;
226         case 'g':
227             gcm_on = 1;
228             sec_servs |= sec_serv_auth;
229             break;
230         case 'r':
231             prog_type = receiver;
232             break;
233         case 's':
234             prog_type = sender;
235             break;
236         case 'd':
237             status = srtp_set_debug_module(optarg_s, 1);
238             if (status) {
239                 printf("error: set debug module (%s) failed\n", optarg_s);
240                 exit(1);
241             }
242             break;
243         case 'l':
244             do_list_mods = 1;
245             break;
246         case 'w':
247             dictfile = optarg_s;
248             break;
249         default:
250             usage(argv[0]);
251         }
252     }
253 
254     if (prog_type == unknown) {
255         if (do_list_mods) {
256             status = srtp_list_debug_modules();
257             if (status) {
258                 printf("error: list of debug modules failed\n");
259                 exit(1);
260             }
261             return 0;
262         } else {
263             printf("error: neither sender [-s] nor receiver [-r] specified\n");
264             usage(argv[0]);
265         }
266     }
267 
268     if ((sec_servs && !input_key) || (!sec_servs && input_key)) {
269         /*
270          * a key must be provided if and only if security services have
271          * been requested
272          */
273         usage(argv[0]);
274     }
275 
276     if (argc != optind_s + 2) {
277         /* wrong number of arguments */
278         usage(argv[0]);
279     }
280 
281     /* get address from arg */
282     address = argv[optind_s++];
283 
284     /* get port from arg */
285     port = atoi(argv[optind_s++]);
286 
287 /* set address */
288 #ifdef HAVE_INET_ATON
289     if (0 == inet_aton(address, &rcvr_addr)) {
290         fprintf(stderr, "%s: cannot parse IP v4 address %s\n", argv[0],
291                 address);
292         exit(1);
293     }
294     if (rcvr_addr.s_addr == INADDR_NONE) {
295         fprintf(stderr, "%s: address error", argv[0]);
296         exit(1);
297     }
298 #else
299     rcvr_addr.s_addr = inet_addr(address);
300     if (0xffffffff == rcvr_addr.s_addr) {
301         fprintf(stderr, "%s: cannot parse IP v4 address %s\n", argv[0],
302                 address);
303         exit(1);
304     }
305 #endif
306 
307     /* open socket */
308     sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
309     if (sock < 0) {
310         int err;
311 #ifdef RTPW_USE_WINSOCK2
312         err = WSAGetLastError();
313 #else
314         err = errno;
315 #endif
316         fprintf(stderr, "%s: couldn't open socket: %d\n", argv[0], err);
317         exit(1);
318     }
319 
320     memset(&name, 0, sizeof(struct sockaddr_in));
321     name.sin_addr = rcvr_addr;
322     name.sin_family = PF_INET;
323     name.sin_port = htons(port);
324 
325     if (ADDR_IS_MULTICAST(rcvr_addr.s_addr)) {
326         if (prog_type == sender) {
327             ret = setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl,
328                              sizeof(ttl));
329             if (ret < 0) {
330                 fprintf(stderr, "%s: Failed to set TTL for multicast group",
331                         argv[0]);
332                 perror("");
333                 exit(1);
334             }
335         }
336 
337         mreq.imr_multiaddr.s_addr = rcvr_addr.s_addr;
338         mreq.imr_interface.s_addr = htonl(INADDR_ANY);
339         ret = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void *)&mreq,
340                          sizeof(mreq));
341         if (ret < 0) {
342             fprintf(stderr, "%s: Failed to join multicast group", argv[0]);
343             perror("");
344             exit(1);
345         }
346     }
347 
348     /* report security services selected on the command line */
349     printf("security services: ");
350     if (sec_servs & sec_serv_conf)
351         printf("confidentiality ");
352     if (sec_servs & sec_serv_auth)
353         printf("message authentication");
354     if (sec_servs == sec_serv_none)
355         printf("none");
356     printf("\n");
357 
358     /* set up the srtp policy and master key */
359     if (sec_servs) {
360         /*
361          * create policy structure, using the default mechanisms but
362          * with only the security services requested on the command line,
363          * using the right SSRC value
364          */
365         switch (sec_servs) {
366         case sec_serv_conf_and_auth:
367             if (gcm_on) {
368 #ifdef GCM
369                 switch (key_size) {
370                 case 128:
371                     srtp_crypto_policy_set_aes_gcm_128_8_auth(&policy.rtp);
372                     srtp_crypto_policy_set_aes_gcm_128_8_auth(&policy.rtcp);
373                     break;
374                 case 256:
375                     srtp_crypto_policy_set_aes_gcm_256_8_auth(&policy.rtp);
376                     srtp_crypto_policy_set_aes_gcm_256_8_auth(&policy.rtcp);
377                     break;
378                 }
379 #else
380                 printf("error: GCM mode only supported when using the OpenSSL "
381                        "or NSS crypto engine.\n");
382                 return 0;
383 #endif
384             } else {
385                 switch (key_size) {
386                 case 128:
387                     srtp_crypto_policy_set_rtp_default(&policy.rtp);
388                     srtp_crypto_policy_set_rtcp_default(&policy.rtcp);
389                     break;
390                 case 256:
391                     srtp_crypto_policy_set_aes_cm_256_hmac_sha1_80(&policy.rtp);
392                     srtp_crypto_policy_set_rtcp_default(&policy.rtcp);
393                     break;
394                 }
395             }
396             break;
397         case sec_serv_conf:
398             if (gcm_on) {
399                 printf(
400                     "error: GCM mode must always be used with auth enabled\n");
401                 return -1;
402             } else {
403                 switch (key_size) {
404                 case 128:
405                     srtp_crypto_policy_set_aes_cm_128_null_auth(&policy.rtp);
406                     srtp_crypto_policy_set_rtcp_default(&policy.rtcp);
407                     break;
408                 case 256:
409                     srtp_crypto_policy_set_aes_cm_256_null_auth(&policy.rtp);
410                     srtp_crypto_policy_set_rtcp_default(&policy.rtcp);
411                     break;
412                 }
413             }
414             break;
415         case sec_serv_auth:
416             if (gcm_on) {
417 #ifdef GCM
418                 switch (key_size) {
419                 case 128:
420                     srtp_crypto_policy_set_aes_gcm_128_8_only_auth(&policy.rtp);
421                     srtp_crypto_policy_set_aes_gcm_128_8_only_auth(
422                         &policy.rtcp);
423                     break;
424                 case 256:
425                     srtp_crypto_policy_set_aes_gcm_256_8_only_auth(&policy.rtp);
426                     srtp_crypto_policy_set_aes_gcm_256_8_only_auth(
427                         &policy.rtcp);
428                     break;
429                 }
430 #else
431                 printf("error: GCM mode only supported when using the OpenSSL "
432                        "crypto engine.\n");
433                 return 0;
434 #endif
435             } else {
436                 srtp_crypto_policy_set_null_cipher_hmac_sha1_80(&policy.rtp);
437                 srtp_crypto_policy_set_rtcp_default(&policy.rtcp);
438             }
439             break;
440         default:
441             printf("error: unknown security service requested\n");
442             return -1;
443         }
444         policy.ssrc.type = ssrc_specific;
445         policy.ssrc.value = ssrc;
446         policy.key = (uint8_t *)key;
447         policy.ekt = NULL;
448         policy.next = NULL;
449         policy.window_size = 128;
450         policy.allow_repeat_tx = 0;
451         policy.rtp.sec_serv = sec_servs;
452         policy.rtcp.sec_serv = sec_serv_none; /* we don't do RTCP anyway */
453 
454         if (gcm_on && tag_size != 8) {
455             policy.rtp.auth_tag_len = tag_size;
456         }
457 
458         /*
459          * read key from hexadecimal or base64 on command line into an octet
460          * string
461          */
462         if (b64_input) {
463             int pad;
464             expected_len = (policy.rtp.cipher_key_len * 4) / 3;
465             len = base64_string_to_octet_string(key, &pad, input_key,
466                                                 expected_len);
467             if (pad != 0) {
468                 fprintf(stderr, "error: padding in base64 unexpected\n");
469                 exit(1);
470             }
471         } else {
472             expected_len = policy.rtp.cipher_key_len * 2;
473             len = hex_string_to_octet_string(key, input_key, expected_len);
474         }
475         /* check that hex string is the right length */
476         if (len < expected_len) {
477             fprintf(stderr, "error: too few digits in key/salt "
478                             "(should be %d digits, found %d)\n",
479                     expected_len, len);
480             exit(1);
481         }
482         if ((int)strlen(input_key) > policy.rtp.cipher_key_len * 2) {
483             fprintf(stderr, "error: too many digits in key/salt "
484                             "(should be %d hexadecimal digits, found %u)\n",
485                     policy.rtp.cipher_key_len * 2, (unsigned)strlen(input_key));
486             exit(1);
487         }
488 
489         printf("set master key/salt to %s/", octet_string_hex_string(key, 16));
490         printf("%s\n", octet_string_hex_string(key + 16, 14));
491 
492     } else {
493         /*
494          * we're not providing security services, so set the policy to the
495          * null policy
496          *
497          * Note that this policy does not conform to the SRTP
498          * specification, since RTCP authentication is required.  However,
499          * the effect of this policy is to turn off SRTP, so that this
500          * application is now a vanilla-flavored RTP application.
501          */
502         srtp_crypto_policy_set_null_cipher_hmac_null(&policy.rtp);
503         srtp_crypto_policy_set_null_cipher_hmac_null(&policy.rtcp);
504         policy.key = (uint8_t *)key;
505         policy.ssrc.type = ssrc_specific;
506         policy.ssrc.value = ssrc;
507         policy.window_size = 0;
508         policy.allow_repeat_tx = 0;
509         policy.ekt = NULL;
510         policy.next = NULL;
511     }
512 
513     if (prog_type == sender) {
514 #if BEW
515         /* bind to local socket (to match crypto policy, if need be) */
516         memset(&local, 0, sizeof(struct sockaddr_in));
517         local.sin_addr.s_addr = htonl(INADDR_ANY);
518         local.sin_port = htons(port);
519         ret = bind(sock, (struct sockaddr *)&local, sizeof(struct sockaddr_in));
520         if (ret < 0) {
521             fprintf(stderr, "%s: bind failed\n", argv[0]);
522             perror("");
523             exit(1);
524         }
525 #endif /* BEW */
526 
527         /* initialize sender's rtp and srtp contexts */
528         snd = rtp_sender_alloc();
529         if (snd == NULL) {
530             fprintf(stderr, "error: malloc() failed\n");
531             exit(1);
532         }
533         rtp_sender_init(snd, sock, name, ssrc);
534         status = rtp_sender_init_srtp(snd, &policy);
535         if (status) {
536             fprintf(stderr, "error: srtp_create() failed with code %d\n",
537                     status);
538             exit(1);
539         }
540 
541         /* open dictionary */
542         dict = fopen(dictfile, "r");
543         if (dict == NULL) {
544             fprintf(stderr, "%s: couldn't open file %s\n", argv[0], dictfile);
545             if (ADDR_IS_MULTICAST(rcvr_addr.s_addr)) {
546                 leave_group(sock, mreq, argv[0]);
547             }
548             exit(1);
549         }
550 
551         /* read words from dictionary, then send them off */
552         while (!interrupted && fgets(word, MAX_WORD_LEN, dict) != NULL) {
553             len = strlen(word) + 1; /* plus one for null */
554 
555             if (len > MAX_WORD_LEN)
556                 printf("error: word %s too large to send\n", word);
557             else {
558                 rtp_sendto(snd, word, len);
559                 printf("sending word: %s", word);
560             }
561             usleep(USEC_RATE);
562         }
563 
564         rtp_sender_deinit_srtp(snd);
565         rtp_sender_dealloc(snd);
566 
567         fclose(dict);
568     } else { /* prog_type == receiver */
569         rtp_receiver_t rcvr;
570 
571         if (bind(sock, (struct sockaddr *)&name, sizeof(name)) < 0) {
572             close(sock);
573             fprintf(stderr, "%s: socket bind error\n", argv[0]);
574             perror(NULL);
575             if (ADDR_IS_MULTICAST(rcvr_addr.s_addr)) {
576                 leave_group(sock, mreq, argv[0]);
577             }
578             exit(1);
579         }
580 
581         rcvr = rtp_receiver_alloc();
582         if (rcvr == NULL) {
583             fprintf(stderr, "error: malloc() failed\n");
584             exit(1);
585         }
586         rtp_receiver_init(rcvr, sock, name, ssrc);
587         status = rtp_receiver_init_srtp(rcvr, &policy);
588         if (status) {
589             fprintf(stderr, "error: srtp_create() failed with code %d\n",
590                     status);
591             exit(1);
592         }
593 
594         /* get next word and loop */
595         while (!interrupted) {
596             len = MAX_WORD_LEN;
597             if (rtp_recvfrom(rcvr, word, &len) > -1)
598                 printf("\tword: %s\n", word);
599         }
600 
601         rtp_receiver_deinit_srtp(rcvr);
602         rtp_receiver_dealloc(rcvr);
603     }
604 
605     if (ADDR_IS_MULTICAST(rcvr_addr.s_addr)) {
606         leave_group(sock, mreq, argv[0]);
607     }
608 
609 #ifdef RTPW_USE_WINSOCK2
610     ret = closesocket(sock);
611 #else
612     ret = close(sock);
613 #endif
614     if (ret < 0) {
615         fprintf(stderr, "%s: Failed to close socket", argv[0]);
616         perror("");
617     }
618 
619     status = srtp_shutdown();
620     if (status) {
621         printf("error: srtp shutdown failed with error code %d\n", status);
622         exit(1);
623     }
624 
625 #ifdef RTPW_USE_WINSOCK2
626     WSACleanup();
627 #endif
628 
629     return 0;
630 }
631 
usage(char * string)632 void usage(char *string)
633 {
634     printf("usage: %s [-d <debug>]* [-k <key> [-a][-e]] "
635            "[-s | -r] dest_ip dest_port\n"
636            "or     %s -l\n"
637            "where  -a use message authentication\n"
638            "       -e <key size> use encryption (use 128 or 256 for key size)\n"
639            "       -g Use AES-GCM mode (must be used with -e)\n"
640            "       -t <tag size> Tag size to use in GCM mode (use 8 or 16)\n"
641            "       -k <key>  sets the srtp master key given in hexadecimal\n"
642            "       -b <key>  sets the srtp master key given in base64\n"
643            "       -s act as rtp sender\n"
644            "       -r act as rtp receiver\n"
645            "       -l list debug modules\n"
646            "       -d <debug> turn on debugging for module <debug>\n"
647            "       -w <wordsfile> use <wordsfile> for input, rather than %s\n",
648            string, string, DICT_FILE);
649     exit(1);
650 }
651 
leave_group(int sock,struct ip_mreq mreq,char * name)652 void leave_group(int sock, struct ip_mreq mreq, char *name)
653 {
654     int ret;
655 
656     ret = setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP, (void *)&mreq,
657                      sizeof(mreq));
658     if (ret < 0) {
659         fprintf(stderr, "%s: Failed to leave multicast group", name);
660         perror("");
661     }
662 }
663 
handle_signal(int signum)664 void handle_signal(int signum)
665 {
666     interrupted = 1;
667     /* Reset handler explicitly, in case we don't have sigaction() (and signal()
668        has BSD semantics), or we don't have SA_RESETHAND */
669     signal(signum, SIG_DFL);
670 }
671 
setup_signal_handler(char * name)672 int setup_signal_handler(char *name)
673 {
674 #if HAVE_SIGACTION
675     struct sigaction act;
676     memset(&act, 0, sizeof(act));
677 
678     act.sa_handler = handle_signal;
679     sigemptyset(&act.sa_mask);
680 #if defined(SA_RESETHAND)
681     act.sa_flags = SA_RESETHAND;
682 #else
683     act.sa_flags = 0;
684 #endif
685     /* Note that we're not setting SA_RESTART; we want recvfrom to return
686      * EINTR when we signal the receiver. */
687 
688     if (sigaction(SIGTERM, &act, NULL) != 0) {
689         fprintf(stderr, "%s: error setting up signal handler", name);
690         perror("");
691         return -1;
692     }
693 #else
694     if (signal(SIGTERM, handle_signal) == SIG_ERR) {
695         fprintf(stderr, "%s: error setting up signal handler", name);
696         perror("");
697         return -1;
698     }
699 #endif
700     return 0;
701 }
702