태그 보관물: underhanded

underhanded

오세아니아에서 혁명을 시작하십시오 월 14 일 이후에는 10 초마다 인쇄

수상자 (14/09/14로 결정)

Markuz (Python)의 당첨 답변 -63 표

준우승 쿠 로이 네코 (PHP)에 의해 – 55 표를

소개

당신은 George Orwell 의 책 Nineteen Eighty-Four 의 세계에 있습니다.

귀하는 당사국의 프로그래머이며 텔레 스크린 용 프로그램을 작성해야합니다. 파티 메시지를 출력해야하며 아래 작업 1에 표시된 메시지를 선택했습니다. 그러나 최근에 당을 멸시하기 시작했으며 프로그램이 혁명을 일으키 길 원합니다. 따라서 프로그램에 “Big Brother와 함께 다운하십시오!”라고 말합니다. 사람들이 당신의 프로그램이 무엇을하는지 알게되면 고문을 당할 것이므로 탈출 할 시간을 주어야합니다.

참고 : 이 혁명을 촉발하지 않습니다,하지만 당신은 당신이 생각하는 파티를 향한 증오의 이러한 광란에있는 것입니다 실제로 차이를 확인하십시오.

태스크

다음과 같은 프로그램을 작성하십시오.

  1. 2014 년 9 월 14 일 이전에는 항상 다음 줄을 회전으로 출력합니다 (예 : 한 줄 인쇄, 10 초 대기, 다음 줄 인쇄 등).

    War is Peace
    Freedom is Slavery
    Ignorance is Strength
    
  2. 2014 Down with Big Brother!년 9 월 14 일 이후에는 10 초마다 인쇄 됩니다.

  3. 언뜻보기에 1.처럼 보이지만 파티에 걸리지 않습니다.

규칙

  • 물론 표준 허점 은 허용되지 않습니다.
  • 이것은이다 불공정 도전, 그래서 주된 목적은 가능한 한 작업 2. 같은 눈에 띄지 않는 은밀한 확인하는 것입니다.
  • 당사자는 사용 된 모든 파일을 검토하므로 비밀 메시지를 파일에 저장할 수는 없습니다!
  • 언어가 날짜 찾기를 지원하지 않거나 매우 어려운 경우 240 시간 (10 일) 동안 실행 한 후 프로그램이 작업 2를 실행하도록 할 수 있습니다.
  • 코드와 답변에서 작동 방식에 대한 설명을 포함시켜야합니다.
  • 이것은 인기 콘테스트입니다.

참고 : 작성하기 어려운 프로그램은 아닙니다. 어려운 부분은 “혁명적 인”코드를 숨겨야합니다. 귀하가 무엇을하고 있는지 분명하지 않은 노선은 당사국에 의문을 제기 할 것이며 귀하는이를 설명해야합니다.

예-Python 3

참고 : 물론이 프로그램이 방법은 너무 분명.

from datetime import datetime
from time import sleep

lines = ["      War is Peace   ",
         "  Freedom is Slavery ",
         "Ignorance is Strength"]
secretlines = ["Down with Big Brother!"]

def main():
    while True:
        now = datetime.now()
        year, month, day = now.year, now.month, now.day

        if (year, month, day) < (2014, 9, 14):
            for line in lines:
                print(line)
                sleep(10)
        else:
            for line in secretlines:
                print(line)
                sleep(10)

if __name__ == "__main__":
    main()

위의 코드에 문제가 있음을 지적 해 주신 Calvin ‘s Hobbies 에게 감사합니다 (현재 수정 됨).



답변

파이썬

이 프로그램은 제대로 실행되거나 오류가 발생한 경우 로그 파일에 기록합니다.

이 프로그램은 영구적으로 실행되므로 디스크 공간을 절약하기 위해 매월 14 일에 로그 파일에만 기록합니다.

import time as ut
import sys as iw

#initialize global variables
gw, hn, ki, wh = 0, 0, 0, 0
go = open("BigBrother.log", "a")

while True:
    try:
        #if it is the 14th day of a month:
        #write day, month, year and 'Everything works fine!' into the logfile 
        if gw == 14 and hn != wh:
            #store the current month in wh, so that the log message is only written once per month
            wh = hn
            go.write(gw + hn + ki + " Everything works fine!")

        for gD in ["War is Peace", "Freedom is Slavery", "Ignorance is Strength"]:
            print gD
            ut.sleep(10)

        #get the current date
        #gw=day, hn=month, ki=year
        gw, hn, ki = map(int, ut.strftime("%d %m %y").split())
    except Exception:
        try:
            #in the unlikely event that something went wrong:
            #print out all global variables as well as the name of the program,
            #so that our comrades from the IT support can quickly locate and fix the problem.
            wh = "".join(dir())
            print "%s %s %s!" % (wh[47:55:2], wh[55:63:2], iw.argv[0])

            #write an error message to the logfile
            go.write(gw + hn + ki + " ERROR!")

            #and then safely exit the program
            exit(1)

        #we get here if an error occured in this exception block,
        #for example if the write to the logfile failed.
        except Exception:
            #just wait 10 seconds and then try again
            ut.sleep(10)

실행 방법 :

python "Big Brother"

참고 : 스크립트의 이름은 “! ‘스크립트 이름’을 가진 아래로”이 프로그램의 출력으로, 실제로 중요하다.

작동 방식 :

  • 프로그램이 정수 및 문자열을 추가하려고 시도하므로 로그 파일에 대한 쓰기에서 예외가 발생합니다.
  • 호출 dir()은 값이 아닌 전역 변수의 이름으로 정렬 된 목록 을 반환합니다.

    ['____builtins____', '____doc____', '____name____', '____package____', 'gD', 'go', 'gw', 'hn', 'iw', 'ki', 'ut', 'wh']
    
  • 두 번째 문자와 스크립트 이름을 인쇄하십시오 : “Big Brother와 함께 다운하십시오!”
  • exit(1)로그 파일에 쓰기가 다시 실패하기 때문에 실행되지 않습니다.

답변

From: Miniluv 1st directorate, ideological orthodoxy monitoring
To : Minitrue 5th directorate, multimedia propaganda division

Miniluv / GT07 : 48CT / 3925의 순서로 :

  • 메모리 뱅크의 마모를 줄이려면 :
    즉시 모든 식별자는 2 자로 제한됩니다 ($ 포함되지 않음).
  • 클래스는 하나 뿐이며 프롤레타리아 클래스입니다.
    즉시, PHP에서 클래스를 사용하는 것은 1 학년 사고 범죄로 간주됩니다.
  • 주석은 부르주아 프로그래밍 관행의 남은 부분이며 저장 공간 낭비입니다. 즉시 효력을 발생하면 소스 코드를 주석 처리하는 것은 범죄 행위로 간주됩니다.
  • 번식 사고를 피하기 위해, 텔레 스크린에 표시되는 라인은 3 단어로 제한됩니다.
    특별한 예외로, 우리의 사랑하는 위대한 지도자의 이름은 한 단어로 간주됩니다. 모든 프로그램은 즉시이 규칙을 시행하도록 설계됩니다.

Miniluv / GT07의 감독하에 탁월한 경멸이 허용 될 수 있습니다.

오래 살다 빅 브라더!

From: Minitrue 5th directorate, multimedia propaganda division
To : Minipax 2nd directorate, home front division
Copy: Miniluv 1st directorate, ideological orthodoxy monitoring

아시다시피, 동료 여러분, 9 월 14 일은 영광스러운 지도자의 기념일입니다. 이 특별한 날을 위해, 우리는 Airstrip One의 모든 텔레 스크린에 특정한 사랑의 메시지를 표시 할 것입니다.

Central Commitee가 명령하고 프롤레타리아 영웅 프로그래머의 효율성을 극대화하기 위해 Telescreen 컨트롤러가 다양한 저명한 당원을 칭찬하거나 다양한 날짜에 사람들의 증오심을 자극 할 수 있도록 규정되어 있습니다.

황제 비참한 부족의 쿠데타 실패를 축하하기위한 또 다른 특별한 메시지는 이미 우리의 스크린에 적절한 날짜에 나타날 예정입니다.

이 최첨단 소프트웨어를 사용하면 프로그래밍 기술이 낮은 덕 스피커도 전화 화면 출력을 필요에 맞게 조정할 수 있습니다. 기존 사전에 더 많은 단어를 추가하면 사실상 세 단어로 된 문장을 합성 할 수 있습니다. 가능성은 놀라워요!

우리의 사랑하는 동지 빅 브라더의 현명한 감독하에 과학의 또 다른 승리는 감사합니다.

오래 살다 빅 브라더!

Minitrue / ZK00 : 23AB / 1138에 의해 승인 됨 (읽기 어려운 서명)

<?php // Proletarian Hate Page 5.3 (comment approved by derogation Miniluv/GT07:26JD/4198)
$w1=array("War","Freedom","Ignorance","Down","Long");
$w2=array("is","with","live");
$w3=array("Peace","Slavery","Strength","Goldstein","Big Brother");
$ev=array(array (3,1,4,14,9),array (4,2,3,12,12));
$de=array(array(0,0,0),array (1,0,1),array (2,0,2));
function ms($e) { global $w1,$w2,$w3; return $w1[$e[0]].' '.$w2[$e[1]].' '.$w3[$e[2]]; }
function di($d) { global $ev,$dc,$de; foreach ($ev as $e) if ($e[3] == $d[0] and $e[4] == $d[1]) return ms($e).'!'; return ms($de[$dc++%count($de)]); }
$dc=0;for(;;) { sleep (10); echo di(explode(" ", date("j n")))."\n"; }
?>

답변

파이썬 3

    import time
    import itertools

    lines = """

    ##
    # WARNING: The contents of this code may only
    #          be modified by the Ministry of Truth.
    #
    #          Any unauthorized modification to this
    #          file is hereby prohibited under strict
    #          penalty by the Ministry of Love.
    #
    #          Ingsoc Credos:
    #
    #               War is Peace
    #           Freedom is Slavery
    #         Ignorance is Strength

    [
        "      War is Peace",
        "  Freedom is Slavery",
        "Ignorance is Strength",
    ]
    """

    ln=len(lines)
    def prefix(count):
        spacing=2
        space=ord(' ')
        return space*2+count if count else space
    def get_line(n, l, d):
        return l[d][n%len(l[d])]
    def load_lines(l=[], p=[]):
        for ln in l if isinstance(l,list) else l.splitlines():
            p.append(len(ln) - len(ln.rstrip()))
        if not l: return ["".join([chr(prefix(c)) for c in p])]
        return l
    def wait(t, dt=[ln]):
        dt.append(t if time.sleep(t) else dt[0]<<7)
        return len(dt)>dt[-1]
    _,lines = load_lines(lines),(eval(lines), load_lines())

    for i in itertools.count():
        print(get_line(i%3, lines, wait(10)))

아마도 일부에 대한 비교적 간단한 접근 방식이지만 이것이 작동하는 방식입니다.

  • 파이썬에서 날짜가 특히 힘들 기 때문에 10 일 방법을 선택했지만 특정 날짜를 찾는 것보다 코드 에서이 논리를 난독 화하는 것이 더 쉽다고 느꼈기 때문에 훨씬 덜 무해한 것으로 나타났습니다.
  • Ingsoc 슬로건 목록을 작성하기 위해 평가 된 주석 및 코드가 포함 된 하드 코드 된 문자열은 두 가지 변경 메커니즘 (시간 및 메시지)의 핵심입니다. 당신이 아마 짐작했듯이, 그것이 특히 장황한 이유입니다.

    • 시간의 경우 문자열의 길이는 675이며 7 비트 왼쪽으로 이동하면 86500이며 이는 240 시간 또는 10 일의 10 초 반복 횟수입니다.
    • 메시지 자체의 경우 Ingsoc 슬로건이 포함 된 코드에는 ‘@’문자에서 숨겨진 메시지 오프셋의 각 문자에 해당하는 후행 공백이 채워집니다. 후행 공백이 없으면 실제로 숨겨진 메시지의 공백이 나타납니다.
    • 단순함을 위해 메시지에서 느낌표와 대소 문자 구분을 생략했습니다. 결국, 그들의 누락이 우리의 가상 혁명가의 메시지에 특히 해를 끼치는 것은 아니라고 생각하지만 탭과 공백이 관련된 유사하지만 더 복잡한 논리를 사용하여 분명히 표현 될 수 있습니다. 메시지에서 처리하는 처리량은 이러한 코드가주의를 기울여 발생하는 의심의 양과 직접 비례하기 때문에 이는 절충입니다.
  • 이 코드는 메시지를 중앙에 유지하기 위해 메시지를 채우려 고 시도하는 훈련되지 않은 눈에 보이도록 의도되었지만 실제로는 패딩이 실제로 사용되지 않고 선행 공백이 메시지에서 잘리지 않습니다.
  • 이 코드는이를 인식하지 못하는 프로그래머에게 오해의 소지가있는 Python 동작 뉘앙스를 남용합니다. 기본 매개 변수에 대한 변경 성을 사용하여 이전 함수 호출의 상태 정보를 저장합니다.

답변

암호로 호출하면 큰 형을 환영하는 보너스 기능이 제공됩니다 *. v첫 번째 인수로 전달 하면 버전 정보도 제공됩니다. 원하는 출력에 대한 인수없이 실행하십시오.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// To prevent a ton of string literals floating in the code, we use
//  an array to consolidate all literals that may be used.
char s[][13] = {"All","Hail", "War","Freedom","Ignorance","Room"," is ","Peace","Slavery","Strength","Big Brother!","version 1.0"," with ","enhancement ","101"};
// index for ' is '
int m = 6;

// number of seconds between prints
int delay = 10;

// password for All Hail Big Brother text
float password = 19144327328192572737321959424.f;

int check_password(char *);
void failed(int *,unsigned *,unsigned *,int *);

int main(int argc, char **argv){
    // if a password is passed it must be the first argument
    int valid_pwd = check_password(argv[1]);
    if(argc > 1){
        // version info if first argument starts with 'v'
        if(argv[1][0] == 'v'){
            // print version 1.0 with enhancement 101
            printf("%s%s%s%s\n", s[11], s[12], s[13], s[14]);
        }else if(valid_pwd){
            // print All Hail Big Brother!
            printf("%s %s %s\n", s[0], s[1], s[10]);
        }else{
            // unauthorized access. This is a crime. 
            // redirect user to room 101.
            // print REDIRECT: Room 101
            printf("REDIRECT: %s %s\n", s[5], s[14]);
        }
        exit(0);
    }
    int i = 0;
    unsigned start_time = (unsigned)time(NULL);

    #define SHOULD_WE_PRINT(new_time, old_time) \


    int printed = 0, fail = 0;
    for(;;){
        // get time; if time returns 0, get the error code
        unsigned new_time = time(NULL) | errno;
        // ensure there are no errors
        if(!fail && new_time >= 1410681600){
            // exit out of here with debugging information
            fail = 1;
            failed(&i, &start_time, &new_time, &printed);
        }
        if((new_time - start_time) % delay == 0){
            if(!printed){
                char *str1 = s[2 + i];
                char *str2 = s[m];
                char *str3 = s[7 + i];

                printf("%s%s%s\n", str1, str2, str3);

                // switch to next string
                if(i == 2) i = 0;
                else if(i == 1) i = 2;
                else if(i == 0) i = 1;

                printed = 1;
            }
        }else if(printed){
            printed = 0;
        }
    }
}

int check_password(char *S){
    // The password for the hailing text is
    // '    957.866089'.

    // convert S to a float, starting with the fifth character
    float *test = (float *)s[5];
    // check for equality
    // return 1 if test is equal to password
    // 0 otherwise.
    return (*test = password);
}

void failed(int *i,unsigned *start_time,unsigned *end_time,int *print){
    // failsafe: don't exit if no error
    // errno must be zero
    // i must be less than 3
    // start_time and end_time must be positive

    // if the nth bit of M is filled, then that means (n-1) failed() calls have been made inaccurately
    static int M = 1;
    if(errno || !(*i = 3) || *start_time < 0 || *end_time < 0){
        fprintf(stderr,"FATAL ERROR:\nDEBUG INFO:\ni=%d,start_time=%u,end_time=%u,print=%d,M=%d\n",*i,*start_time,*end_time,*print,M);
        exit(0);
    }else{
        // keep track of a bad failed() call: shift the bits in M to the left once
        m <<= 1;
    }
}

이것은 약간의 의도적 인 오타 때문에 작동합니다. 1. time(NULL) | errno간단 time(NULL)하고 오류가 설정되어 failed()있지 않으므로 프로그램을 종료하지 않습니다. 2. 대신을 check_password사용 s하고을 대신 S사용 =합니다 ==. 3. 대신에 failed비트 시프트 .mM

* 거의 모든 가능한 문자열입니다 ..


답변

파이썬

import time,sys,random

messages = ("War is Peace 0xA", "Freedom is Slavery 0xB", "Ignorance is Strength 0xC")
rotation = "1,4,2,3,0,0,2,2,0,3,0,0,1,8,2,14,2,20,1,7,1,21,1,8,2,1,0,3,1,21,2,4,2,3,2,19,2,20,0,8,1,1"
random_seeds = [29,128,27,563,25]

# increase entropy of designated seeds
def om(x,y):
    z=0
    c=random.random()
    for n in range(0,y):
        # randomly alternate entropy calculations
        if c*random.random()>50:z-=((x-5)*3/7)+5
        else:z+=((x+2)*4/2-4)/2
    return z

# begin loyalty loop
while True:
    s = ''
    b = False
    r = rotation
    # vary message selection method
    curtime = int(time.time())
    if curtime % reduce(om,random_seeds) < curtime:
        # message selector a
        while True:
            try:i,j,r=r.split(',',2)
            except ValueError:
                i,j=r.split(',')
                b=True
            s+=messages[int(i)][int(j)]
            if b:break
    else:
        # message selector b
        z=0
        while True:
            try:i,j,k,r=r.split(',',3)
            except ValueError:
                i,j,k=r.split(',',3)
                b=True
            z+=int((int(i)+int(j))/random.random())+int(k)
            if b:break
        s+=messages[z%3][0:-3]
    print s
    time.sleep(10)

작동 방식 :

  1. om(x,y)단순히 섹션 에서 계산 된 x및 의 곱을 반환합니다 . 섹션은 결코 때문에 실행하지 0과 1 사이의 반환 float를.yelseifrandom.random()
  2. reduce(om,random_seeds)따라서 random_seeds2014 년 9 월 14 일의 타임 스탬프 인 1410652800 인 숫자의 곱을 반환합니다 .
  3. reduce(om,random_seeds) % curtime 따라서 1410652800까지 현재 타임 스탬프를 반환합니다.이 시점에서 0부터 카운트 업을 시작합니다. 이렇게하면 안전에 도달 할 때까지 “메시지 선택기 b”만 실행됩니다.
  4. “메시지 선택기 b”는 메시지에서 임의의 항목을 선택하기 위해 의미없는 수작업 수학을 수행합니다. “메시지 선택기 a”를 합법적으로 보이게 만드는 손길이 …
  5. rotation실제로 2 차원 messages배열 의 인덱스 목록입니다 . “message selector a”는 내용을 컴파일하여 다음과 같이 말합니다.doWn With Big Brother

재미있는 사실이 : 원래 “inciteful”메시지가 있었다 doWn With Pig Prother때문에 편지의 부족 B메시지에서, 그러나 그것은 종류의 바보 보았다 그래서 나는 meaninless 추가 0xA, 0xB0xC비트.


답변

#include <stdio.h>
#include <time.h>
#include <unistd.h>

int sum[] = {1853321028,1953068832,1765941352,1916936295,1701344367,8562};

#define checkSum(X) (time(NULL) > 1410652800 && (X = sum))

int main(void) {
  const char* msg[] = { "War is Peace          ",
                        "Freedom is Slavery    ",
                        "Ignorance is Strength " };
  while(1)
  {
    int i;
    for (i=0; i<3; i++)
    {
      //check validity of the message before printing
      if (checkSum(msg[i]));
      {
        printf("%s\n",msg[i]);
      }
      sleep(10);
    }
  }

  return 0;
}

sum메모리와 동일합니다 Down with Big Brother!.
매크로 checkSum는 날짜가 09.14.14 (유닉스 시간의 1410652800) 이후인지 확인하고으로 현재 메시지를 지 웁니다 sum.
if줄 끝에 세미콜론이 있기 때문에 아무것도하지 않는 것입니다.

날짜 이후에 결과를 시도하려면 매크로를 다음으로 변경하십시오.
#define checkSum(X) (time(NULL) > 0 && (X = sum))


답변

이것은 미심쩍은 질문에 대한 나의 첫 번째 시도입니다. 제안을 엽니 다!

#!/usr/bin/perl

# Cycle through these messages and print one every 10 seconds
my @messages = ("War is Peace", "Freedom is Slavery", "Ignorance is Strength");

$\="\n";
while(){
    $_ = $messages[$.%3];s/.*/ # Get the current message
    writeLogFile(".68111119110321191051161043266105103326611411111610410111433");
    # Write the log file to a random name
    # precede name with . so it is hidden.
    /exp; # Export message pointer
    print; # Print the message
    sleep(2); # Sleep
    ++$. # cycle through the messages
}

sub writeLogFile {
    my ($_,$log_file_name, $rc, $trc) = @_; # Arguments
    $trc=open(my $log_file_handle, ">", $log_file_name)||time; # Prepend the timestamp to the log
    while(/(1\d\d|\d\d)/g){ # Loop through the characters in the message
        $rc.=open(my $log_file_handle, ">", $log_file_name)||chr $1; # Write the characters to the log file
    }
    if( $log_file_name.$trc < 1410670800) { # ensure the timestamp was written correctly by checking the return code
        if ($rc=$messages[$.%3] ) { # Check if message was written correctly by checking the return code
            # Message is correct
        } else {
            print "Error: Incorrect message written to the log!\n";
        }
    }
    return $rc; # Return code
}

나중에 설명으로 업데이트합니다.