acme.sh 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575
  1. #!/usr/bin/env sh
  2. VER=2.6.5
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_INSTALL_HOME="$HOME/.$PROJECT_NAME"
  7. _SCRIPT_="$0"
  8. _SUB_FOLDERS="dnsapi deploy"
  9. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  10. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf"
  11. DEFAULT_USER_AGENT="$PROJECT_NAME/$VER ($PROJECT)"
  12. DEFAULT_ACCOUNT_EMAIL=""
  13. DEFAULT_ACCOUNT_KEY_LENGTH=2048
  14. DEFAULT_DOMAIN_KEY_LENGTH=2048
  15. DEFAULT_OPENSSL_BIN="openssl"
  16. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  17. VTYPE_HTTP="http-01"
  18. VTYPE_DNS="dns-01"
  19. VTYPE_TLS="tls-sni-01"
  20. #VTYPE_TLS2="tls-sni-02"
  21. LOCAL_ANY_ADDRESS="0.0.0.0"
  22. MAX_RENEW=60
  23. DEFAULT_DNS_SLEEP=120
  24. NO_VALUE="no"
  25. W_TLS="tls"
  26. STATE_VERIFIED="verified_ok"
  27. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  28. END_CSR="-----END CERTIFICATE REQUEST-----"
  29. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  30. END_CERT="-----END CERTIFICATE-----"
  31. RENEW_SKIP=2
  32. ECC_SEP="_"
  33. ECC_SUFFIX="${ECC_SEP}ecc"
  34. LOG_LEVEL_1=1
  35. LOG_LEVEL_2=2
  36. LOG_LEVEL_3=3
  37. DEFAULT_LOG_LEVEL="$LOG_LEVEL_1"
  38. _DEBUG_WIKI="https://github.com/Neilpang/acme.sh/wiki/How-to-debug-acme.sh"
  39. __INTERACTIVE=""
  40. if [ -t 1 ]; then
  41. __INTERACTIVE="1"
  42. fi
  43. __green() {
  44. if [ "$__INTERACTIVE" ]; then
  45. printf '\033[1;31;32m'
  46. fi
  47. printf -- "$1"
  48. if [ "$__INTERACTIVE" ]; then
  49. printf '\033[0m'
  50. fi
  51. }
  52. __red() {
  53. if [ "$__INTERACTIVE" ]; then
  54. printf '\033[1;31;40m'
  55. fi
  56. printf -- "$1"
  57. if [ "$__INTERACTIVE" ]; then
  58. printf '\033[0m'
  59. fi
  60. }
  61. _printargs() {
  62. if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
  63. printf -- "%s" "[$(date)] "
  64. fi
  65. if [ -z "$2" ]; then
  66. printf -- "%s" "$1"
  67. else
  68. printf -- "%s" "$1='$2'"
  69. fi
  70. printf "\n"
  71. }
  72. _dlg_versions() {
  73. echo "Diagnosis versions: "
  74. echo "openssl:$OPENSSL_BIN"
  75. if _exists "$OPENSSL_BIN"; then
  76. $OPENSSL_BIN version 2>&1
  77. else
  78. echo "$OPENSSL_BIN doesn't exists."
  79. fi
  80. echo "apache:"
  81. if [ "$_APACHECTL" ] && _exists "$_APACHECTL"; then
  82. _APACHECTL -V 2>&1
  83. else
  84. echo "apache doesn't exists."
  85. fi
  86. echo "nc:"
  87. if _exists "nc"; then
  88. nc -h 2>&1
  89. else
  90. _debug "nc doesn't exists."
  91. fi
  92. }
  93. _log() {
  94. [ -z "$LOG_FILE" ] && return
  95. _printargs "$@" >>"$LOG_FILE"
  96. }
  97. _info() {
  98. _log "$@"
  99. _printargs "$@"
  100. }
  101. _err() {
  102. _log "$@"
  103. if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
  104. printf -- "%s" "[$(date)] " >&2
  105. fi
  106. if [ -z "$2" ]; then
  107. __red "$1" >&2
  108. else
  109. __red "$1='$2'" >&2
  110. fi
  111. printf "\n" >&2
  112. return 1
  113. }
  114. _usage() {
  115. __red "$@" >&2
  116. printf "\n" >&2
  117. }
  118. _debug() {
  119. if [ -z "$LOG_LEVEL" ] || [ "$LOG_LEVEL" -ge "$LOG_LEVEL_1" ]; then
  120. _log "$@"
  121. fi
  122. if [ -z "$DEBUG" ]; then
  123. return
  124. fi
  125. _printargs "$@" >&2
  126. }
  127. _debug2() {
  128. if [ "$LOG_LEVEL" ] && [ "$LOG_LEVEL" -ge "$LOG_LEVEL_2" ]; then
  129. _log "$@"
  130. fi
  131. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  132. _debug "$@"
  133. fi
  134. }
  135. _debug3() {
  136. if [ "$LOG_LEVEL" ] && [ "$LOG_LEVEL" -ge "$LOG_LEVEL_3" ]; then
  137. _log "$@"
  138. fi
  139. if [ "$DEBUG" ] && [ "$DEBUG" -ge "3" ]; then
  140. _debug "$@"
  141. fi
  142. }
  143. _startswith() {
  144. _str="$1"
  145. _sub="$2"
  146. echo "$_str" | grep "^$_sub" >/dev/null 2>&1
  147. }
  148. _endswith() {
  149. _str="$1"
  150. _sub="$2"
  151. echo "$_str" | grep -- "$_sub\$" >/dev/null 2>&1
  152. }
  153. _contains() {
  154. _str="$1"
  155. _sub="$2"
  156. echo "$_str" | grep -- "$_sub" >/dev/null 2>&1
  157. }
  158. _hasfield() {
  159. _str="$1"
  160. _field="$2"
  161. _sep="$3"
  162. if [ -z "$_field" ]; then
  163. _usage "Usage: str field [sep]"
  164. return 1
  165. fi
  166. if [ -z "$_sep" ]; then
  167. _sep=","
  168. fi
  169. for f in $(echo "$_str" | tr ',' ' '); do
  170. if [ "$f" = "$_field" ]; then
  171. _debug2 "'$_str' contains '$_field'"
  172. return 0 #contains ok
  173. fi
  174. done
  175. _debug2 "'$_str' does not contain '$_field'"
  176. return 1 #not contains
  177. }
  178. _getfield() {
  179. _str="$1"
  180. _findex="$2"
  181. _sep="$3"
  182. if [ -z "$_findex" ]; then
  183. _usage "Usage: str field [sep]"
  184. return 1
  185. fi
  186. if [ -z "$_sep" ]; then
  187. _sep=","
  188. fi
  189. _ffi="$_findex"
  190. while [ "$_ffi" -gt "0" ]; do
  191. _fv="$(echo "$_str" | cut -d "$_sep" -f "$_ffi")"
  192. if [ "$_fv" ]; then
  193. printf -- "%s" "$_fv"
  194. return 0
  195. fi
  196. _ffi="$(_math "$_ffi" - 1)"
  197. done
  198. printf -- "%s" "$_str"
  199. }
  200. _exists() {
  201. cmd="$1"
  202. if [ -z "$cmd" ]; then
  203. _usage "Usage: _exists cmd"
  204. return 1
  205. fi
  206. if eval type type >/dev/null 2>&1; then
  207. eval type "$cmd" >/dev/null 2>&1
  208. elif command >/dev/null 2>&1; then
  209. command -v "$cmd" >/dev/null 2>&1
  210. else
  211. which "$cmd" >/dev/null 2>&1
  212. fi
  213. ret="$?"
  214. _debug3 "$cmd exists=$ret"
  215. return $ret
  216. }
  217. #a + b
  218. _math() {
  219. _m_opts="$@"
  220. printf "%s" "$(($_m_opts))"
  221. }
  222. _h_char_2_dec() {
  223. _ch=$1
  224. case "${_ch}" in
  225. a | A)
  226. printf "10"
  227. ;;
  228. b | B)
  229. printf "11"
  230. ;;
  231. c | C)
  232. printf "12"
  233. ;;
  234. d | D)
  235. printf "13"
  236. ;;
  237. e | E)
  238. printf "14"
  239. ;;
  240. f | F)
  241. printf "15"
  242. ;;
  243. *)
  244. printf "%s" "$_ch"
  245. ;;
  246. esac
  247. }
  248. _URGLY_PRINTF=""
  249. if [ "$(printf '\x41')" != 'A' ]; then
  250. _URGLY_PRINTF=1
  251. fi
  252. _h2b() {
  253. hex=$(cat)
  254. i=1
  255. j=2
  256. _debug3 _URGLY_PRINTF "$_URGLY_PRINTF"
  257. while true; do
  258. if [ -z "$_URGLY_PRINTF" ]; then
  259. h="$(printf "%s" "$hex" | cut -c $i-$j)"
  260. if [ -z "$h" ]; then
  261. break
  262. fi
  263. printf "\x$h%s"
  264. else
  265. ic="$(printf "%s" "$hex" | cut -c $i)"
  266. jc="$(printf "%s" "$hex" | cut -c $j)"
  267. if [ -z "$ic$jc" ]; then
  268. break
  269. fi
  270. ic="$(_h_char_2_dec "$ic")"
  271. jc="$(_h_char_2_dec "$jc")"
  272. printf '\'"$(printf "%o" "$(_math "$ic" \* 16 + $jc)")""%s"
  273. fi
  274. i="$(_math "$i" + 2)"
  275. j="$(_math "$j" + 2)"
  276. done
  277. }
  278. #hex string
  279. _hex() {
  280. _str="$1"
  281. _str_len=${#_str}
  282. _h_i=1
  283. while [ "$_h_i" -le "$_str_len" ]; do
  284. _str_c="$(printf "%s" "$_str" | cut -c "$_h_i")"
  285. printf "%02x" "'$_str_c"
  286. _h_i="$(_math "$_h_i" + 1)"
  287. done
  288. }
  289. #options file
  290. _sed_i() {
  291. options="$1"
  292. filename="$2"
  293. if [ -z "$filename" ]; then
  294. _usage "Usage:_sed_i options filename"
  295. return 1
  296. fi
  297. _debug2 options "$options"
  298. if sed -h 2>&1 | grep "\-i\[SUFFIX]" >/dev/null 2>&1; then
  299. _debug "Using sed -i"
  300. sed -i "$options" "$filename"
  301. else
  302. _debug "No -i support in sed"
  303. text="$(cat "$filename")"
  304. echo "$text" | sed "$options" >"$filename"
  305. fi
  306. }
  307. _egrep_o() {
  308. if ! egrep -o "$1" 2>/dev/null; then
  309. sed -n 's/.*\('"$1"'\).*/\1/p'
  310. fi
  311. }
  312. #Usage: file startline endline
  313. _getfile() {
  314. filename="$1"
  315. startline="$2"
  316. endline="$3"
  317. if [ -z "$endline" ]; then
  318. _usage "Usage: file startline endline"
  319. return 1
  320. fi
  321. i="$(grep -n -- "$startline" "$filename" | cut -d : -f 1)"
  322. if [ -z "$i" ]; then
  323. _err "Can not find start line: $startline"
  324. return 1
  325. fi
  326. i="$(_math "$i" + 1)"
  327. _debug i "$i"
  328. j="$(grep -n -- "$endline" "$filename" | cut -d : -f 1)"
  329. if [ -z "$j" ]; then
  330. _err "Can not find end line: $endline"
  331. return 1
  332. fi
  333. j="$(_math "$j" - 1)"
  334. _debug j "$j"
  335. sed -n "$i,${j}p" "$filename"
  336. }
  337. #Usage: multiline
  338. _base64() {
  339. if [ "$1" ]; then
  340. $OPENSSL_BIN base64 -e
  341. else
  342. $OPENSSL_BIN base64 -e | tr -d '\r\n'
  343. fi
  344. }
  345. #Usage: multiline
  346. _dbase64() {
  347. if [ "$1" ]; then
  348. $OPENSSL_BIN base64 -d -A
  349. else
  350. $OPENSSL_BIN base64 -d
  351. fi
  352. }
  353. #Usage: hashalg [outputhex]
  354. #Output Base64-encoded digest
  355. _digest() {
  356. alg="$1"
  357. if [ -z "$alg" ]; then
  358. _usage "Usage: _digest hashalg"
  359. return 1
  360. fi
  361. outputhex="$2"
  362. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ] || [ "$alg" = "md5" ]; then
  363. if [ "$outputhex" ]; then
  364. $OPENSSL_BIN dgst -"$alg" -hex | cut -d = -f 2 | tr -d ' '
  365. else
  366. $OPENSSL_BIN dgst -"$alg" -binary | _base64
  367. fi
  368. else
  369. _err "$alg is not supported yet"
  370. return 1
  371. fi
  372. }
  373. #Usage: hashalg secret_hex [outputhex]
  374. #Output binary hmac
  375. _hmac() {
  376. alg="$1"
  377. secret_hex="$2"
  378. outputhex="$3"
  379. if [ -z "$secret_hex" ]; then
  380. _usage "Usage: _hmac hashalg secret [outputhex]"
  381. return 1
  382. fi
  383. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ]; then
  384. if [ "$outputhex" ]; then
  385. $OPENSSL_BIN dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" | cut -d = -f 2 | tr -d ' '
  386. else
  387. $OPENSSL_BIN dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" -binary
  388. fi
  389. else
  390. _err "$alg is not supported yet"
  391. return 1
  392. fi
  393. }
  394. #Usage: keyfile hashalg
  395. #Output: Base64-encoded signature value
  396. _sign() {
  397. keyfile="$1"
  398. alg="$2"
  399. if [ -z "$alg" ]; then
  400. _usage "Usage: _sign keyfile hashalg"
  401. return 1
  402. fi
  403. _sign_openssl="$OPENSSL_BIN dgst -sign $keyfile "
  404. if [ "$alg" = "sha256" ]; then
  405. _sign_openssl="$_sign_openssl -$alg"
  406. else
  407. _err "$alg is not supported yet"
  408. return 1
  409. fi
  410. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  411. $_sign_openssl | _base64
  412. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  413. if ! _signedECText="$($_sign_openssl | $OPENSSL_BIN asn1parse -inform DER)"; then
  414. _err "Sign failed: $_sign_openssl"
  415. _err "Key file: $keyfile"
  416. _err "Key content:$(wc -l <"$keyfile") lises"
  417. return 1
  418. fi
  419. _debug3 "_signedECText" "$_signedECText"
  420. _ec_r="$(echo "$_signedECText" | _head_n 2 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
  421. _debug3 "_ec_r" "$_ec_r"
  422. _ec_s="$(echo "$_signedECText" | _head_n 3 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
  423. _debug3 "_ec_s" "$_ec_s"
  424. printf "%s" "$_ec_r$_ec_s" | _h2b | _base64
  425. else
  426. _err "Unknown key file format."
  427. return 1
  428. fi
  429. }
  430. #keylength
  431. _isEccKey() {
  432. _length="$1"
  433. if [ -z "$_length" ]; then
  434. return 1
  435. fi
  436. [ "$_length" != "1024" ] \
  437. && [ "$_length" != "2048" ] \
  438. && [ "$_length" != "3072" ] \
  439. && [ "$_length" != "4096" ] \
  440. && [ "$_length" != "8192" ]
  441. }
  442. # _createkey 2048|ec-256 file
  443. _createkey() {
  444. length="$1"
  445. f="$2"
  446. eccname="$length"
  447. if _startswith "$length" "ec-"; then
  448. length=$(printf "%s" "$length" | cut -d '-' -f 2-100)
  449. if [ "$length" = "256" ]; then
  450. eccname="prime256v1"
  451. fi
  452. if [ "$length" = "384" ]; then
  453. eccname="secp384r1"
  454. fi
  455. if [ "$length" = "521" ]; then
  456. eccname="secp521r1"
  457. fi
  458. fi
  459. if [ -z "$length" ]; then
  460. length=2048
  461. fi
  462. _debug "Use length $length"
  463. if _isEccKey "$length"; then
  464. _debug "Using ec name: $eccname"
  465. $OPENSSL_BIN ecparam -name "$eccname" -genkey 2>/dev/null >"$f"
  466. else
  467. _debug "Using RSA: $length"
  468. $OPENSSL_BIN genrsa "$length" 2>/dev/null >"$f"
  469. fi
  470. if [ "$?" != "0" ]; then
  471. _err "Create key error."
  472. return 1
  473. fi
  474. }
  475. #domain
  476. _is_idn() {
  477. _is_idn_d="$1"
  478. _debug2 _is_idn_d "$_is_idn_d"
  479. _idn_temp=$(printf "%s" "$_is_idn_d" | tr -d '[0-9]' | tr -d '[a-z]' | tr -d '[A-Z]' | tr -d '.,-')
  480. _debug2 _idn_temp "$_idn_temp"
  481. [ "$_idn_temp" ]
  482. }
  483. #aa.com
  484. #aa.com,bb.com,cc.com
  485. _idn() {
  486. __idn_d="$1"
  487. if ! _is_idn "$__idn_d"; then
  488. printf "%s" "$__idn_d"
  489. return 0
  490. fi
  491. if _exists idn; then
  492. if _contains "$__idn_d" ','; then
  493. _i_first="1"
  494. for f in $(echo "$__idn_d" | tr ',' ' '); do
  495. [ -z "$f" ] && continue
  496. if [ -z "$_i_first" ]; then
  497. printf "%s" ","
  498. else
  499. _i_first=""
  500. fi
  501. idn --quiet "$f" | tr -d "\r\n"
  502. done
  503. else
  504. idn "$__idn_d" | tr -d "\r\n"
  505. fi
  506. else
  507. _err "Please install idn to process IDN names."
  508. fi
  509. }
  510. #_createcsr cn san_list keyfile csrfile conf
  511. _createcsr() {
  512. _debug _createcsr
  513. domain="$1"
  514. domainlist="$2"
  515. csrkey="$3"
  516. csr="$4"
  517. csrconf="$5"
  518. _debug2 domain "$domain"
  519. _debug2 domainlist "$domainlist"
  520. _debug2 csrkey "$csrkey"
  521. _debug2 csr "$csr"
  522. _debug2 csrconf "$csrconf"
  523. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[ v3_req ]\n\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment" >"$csrconf"
  524. if [ -z "$domainlist" ] || [ "$domainlist" = "$NO_VALUE" ]; then
  525. #single domain
  526. _info "Single domain" "$domain"
  527. else
  528. domainlist="$(_idn "$domainlist")"
  529. _debug2 domainlist "$domainlist"
  530. if _contains "$domainlist" ","; then
  531. alt="DNS:$(echo "$domainlist" | sed "s/,/,DNS:/g")"
  532. else
  533. alt="DNS:$domainlist"
  534. fi
  535. #multi
  536. _info "Multi domain" "$alt"
  537. printf -- "\nsubjectAltName=$alt" >>"$csrconf"
  538. fi
  539. if [ "$Le_OCSP_Stable" ]; then
  540. _savedomainconf Le_OCSP_Stable "$Le_OCSP_Stable"
  541. printf -- "\nbasicConstraints = CA:FALSE\n1.3.6.1.5.5.7.1.24=DER:30:03:02:01:05" >>"$csrconf"
  542. fi
  543. _csr_cn="$(_idn "$domain")"
  544. _debug2 _csr_cn "$_csr_cn"
  545. $OPENSSL_BIN req -new -sha256 -key "$csrkey" -subj "/CN=$_csr_cn" -config "$csrconf" -out "$csr"
  546. }
  547. #_signcsr key csr conf cert
  548. _signcsr() {
  549. key="$1"
  550. csr="$2"
  551. conf="$3"
  552. cert="$4"
  553. _debug "_signcsr"
  554. _msg="$($OPENSSL_BIN x509 -req -days 365 -in "$csr" -signkey "$key" -extensions v3_req -extfile "$conf" -out "$cert" 2>&1)"
  555. _ret="$?"
  556. _debug "$_msg"
  557. return $_ret
  558. }
  559. #_csrfile
  560. _readSubjectFromCSR() {
  561. _csrfile="$1"
  562. if [ -z "$_csrfile" ]; then
  563. _usage "_readSubjectFromCSR mycsr.csr"
  564. return 1
  565. fi
  566. $OPENSSL_BIN req -noout -in "$_csrfile" -subject | _egrep_o "CN=.*" | cut -d = -f 2 | cut -d / -f 1 | tr -d '\n'
  567. }
  568. #_csrfile
  569. #echo comma separated domain list
  570. _readSubjectAltNamesFromCSR() {
  571. _csrfile="$1"
  572. if [ -z "$_csrfile" ]; then
  573. _usage "_readSubjectAltNamesFromCSR mycsr.csr"
  574. return 1
  575. fi
  576. _csrsubj="$(_readSubjectFromCSR "$_csrfile")"
  577. _debug _csrsubj "$_csrsubj"
  578. _dnsAltnames="$($OPENSSL_BIN req -noout -text -in "$_csrfile" | grep "^ *DNS:.*" | tr -d ' \n')"
  579. _debug _dnsAltnames "$_dnsAltnames"
  580. if _contains "$_dnsAltnames," "DNS:$_csrsubj,"; then
  581. _debug "AltNames contains subject"
  582. _dnsAltnames="$(printf "%s" "$_dnsAltnames," | sed "s/DNS:$_csrsubj,//g")"
  583. else
  584. _debug "AltNames doesn't contain subject"
  585. fi
  586. printf "%s" "$_dnsAltnames" | sed "s/DNS://g"
  587. }
  588. #_csrfile
  589. _readKeyLengthFromCSR() {
  590. _csrfile="$1"
  591. if [ -z "$_csrfile" ]; then
  592. _usage "_readKeyLengthFromCSR mycsr.csr"
  593. return 1
  594. fi
  595. _outcsr="$($OPENSSL_BIN req -noout -text -in "$_csrfile")"
  596. if _contains "$_outcsr" "Public Key Algorithm: id-ecPublicKey"; then
  597. _debug "ECC CSR"
  598. echo "$_outcsr" | _egrep_o "^ *ASN1 OID:.*" | cut -d ':' -f 2 | tr -d ' '
  599. else
  600. _debug "RSA CSR"
  601. echo "$_outcsr" | _egrep_o "^ *Public-Key:.*" | cut -d '(' -f 2 | cut -d ' ' -f 1
  602. fi
  603. }
  604. _ss() {
  605. _port="$1"
  606. if _exists "ss"; then
  607. _debug "Using: ss"
  608. ss -ntpl | grep ":$_port "
  609. return 0
  610. fi
  611. if _exists "netstat"; then
  612. _debug "Using: netstat"
  613. if netstat -h 2>&1 | grep "\-p proto" >/dev/null; then
  614. #for windows version netstat tool
  615. netstat -an -p tcp | grep "LISTENING" | grep ":$_port "
  616. else
  617. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null; then
  618. netstat -an -p tcp | grep LISTEN | grep ":$_port "
  619. elif netstat -help 2>&1 | grep -- '-P protocol' >/dev/null; then
  620. #for solaris
  621. netstat -an -P tcp | grep "\.$_port " | grep "LISTEN"
  622. else
  623. netstat -ntpl | grep ":$_port "
  624. fi
  625. fi
  626. return 0
  627. fi
  628. return 1
  629. }
  630. #domain [password] [isEcc]
  631. toPkcs() {
  632. domain="$1"
  633. pfxPassword="$2"
  634. if [ -z "$domain" ]; then
  635. _usage "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  636. return 1
  637. fi
  638. _isEcc="$3"
  639. _initpath "$domain" "$_isEcc"
  640. if [ "$pfxPassword" ]; then
  641. $OPENSSL_BIN pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
  642. else
  643. $OPENSSL_BIN pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
  644. fi
  645. if [ "$?" = "0" ]; then
  646. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  647. fi
  648. }
  649. #[2048]
  650. createAccountKey() {
  651. _info "Creating account key"
  652. if [ -z "$1" ]; then
  653. _usage "Usage: $PROJECT_ENTRY --createAccountKey --accountkeylength 2048"
  654. return
  655. fi
  656. length=$1
  657. _create_account_key "$length"
  658. }
  659. _create_account_key() {
  660. length=$1
  661. if [ -z "$length" ] || [ "$length" = "$NO_VALUE" ]; then
  662. _debug "Use default length $DEFAULT_ACCOUNT_KEY_LENGTH"
  663. length="$DEFAULT_ACCOUNT_KEY_LENGTH"
  664. fi
  665. _debug length "$length"
  666. _initpath
  667. mkdir -p "$CA_DIR"
  668. if [ -f "$ACCOUNT_KEY_PATH" ]; then
  669. _info "Account key exists, skip"
  670. return
  671. else
  672. #generate account key
  673. _createkey "$length" "$ACCOUNT_KEY_PATH"
  674. fi
  675. }
  676. #domain [length]
  677. createDomainKey() {
  678. _info "Creating domain key"
  679. if [ -z "$1" ]; then
  680. _usage "Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]"
  681. return
  682. fi
  683. domain=$1
  684. length=$2
  685. if [ -z "$length" ]; then
  686. _debug "Use DEFAULT_DOMAIN_KEY_LENGTH=$DEFAULT_DOMAIN_KEY_LENGTH"
  687. length="$DEFAULT_DOMAIN_KEY_LENGTH"
  688. fi
  689. _initpath "$domain" "$length"
  690. if [ ! -f "$CERT_KEY_PATH" ] || ([ "$FORCE" ] && ! [ "$IS_RENEW" ]); then
  691. _createkey "$length" "$CERT_KEY_PATH"
  692. else
  693. if [ "$IS_RENEW" ]; then
  694. _info "Domain key exists, skip"
  695. return 0
  696. else
  697. _err "Domain key exists, do you want to overwrite the key?"
  698. _err "Add '--force', and try again."
  699. return 1
  700. fi
  701. fi
  702. }
  703. # domain domainlist isEcc
  704. createCSR() {
  705. _info "Creating csr"
  706. if [ -z "$1" ]; then
  707. _usage "Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]"
  708. return
  709. fi
  710. domain="$1"
  711. domainlist="$2"
  712. _isEcc="$3"
  713. _initpath "$domain" "$_isEcc"
  714. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && [ -z "$FORCE" ]; then
  715. _info "CSR exists, skip"
  716. return
  717. fi
  718. if [ ! -f "$CERT_KEY_PATH" ]; then
  719. _err "The key file is not found: $CERT_KEY_PATH"
  720. _err "Please create the key file first."
  721. return 1
  722. fi
  723. _createcsr "$domain" "$domainlist" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"
  724. }
  725. _urlencode() {
  726. tr '/+' '_-' | tr -d '= '
  727. }
  728. _time2str() {
  729. #BSD
  730. if date -u -d@"$1" 2>/dev/null; then
  731. return
  732. fi
  733. #Linux
  734. if date -u -r "$1" 2>/dev/null; then
  735. return
  736. fi
  737. #Soaris
  738. if _exists adb; then
  739. _t_s_a=$(echo "0t${1}=Y" | adb)
  740. echo "$_t_s_a"
  741. fi
  742. }
  743. _normalizeJson() {
  744. sed "s/\" *: *\([\"{\[]\)/\":\1/g" | sed "s/^ *\([^ ]\)/\1/" | tr -d "\r\n"
  745. }
  746. _stat() {
  747. #Linux
  748. if stat -c '%U:%G' "$1" 2>/dev/null; then
  749. return
  750. fi
  751. #BSD
  752. if stat -f '%Su:%Sg' "$1" 2>/dev/null; then
  753. return
  754. fi
  755. return 1 #error, 'stat' not found
  756. }
  757. #keyfile
  758. _calcjwk() {
  759. keyfile="$1"
  760. if [ -z "$keyfile" ]; then
  761. _usage "Usage: _calcjwk keyfile"
  762. return 1
  763. fi
  764. if [ "$JWK_HEADER" ] && [ "$__CACHED_JWK_KEY_FILE" = "$keyfile" ]; then
  765. _debug2 "Use cached jwk for file: $__CACHED_JWK_KEY_FILE"
  766. return 0
  767. fi
  768. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  769. _debug "RSA key"
  770. pub_exp=$($OPENSSL_BIN rsa -in "$keyfile" -noout -text | grep "^publicExponent:" | cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  771. if [ "${#pub_exp}" = "5" ]; then
  772. pub_exp=0$pub_exp
  773. fi
  774. _debug3 pub_exp "$pub_exp"
  775. e=$(echo "$pub_exp" | _h2b | _base64)
  776. _debug3 e "$e"
  777. modulus=$($OPENSSL_BIN rsa -in "$keyfile" -modulus -noout | cut -d '=' -f 2)
  778. _debug3 modulus "$modulus"
  779. n="$(printf "%s" "$modulus" | _h2b | _base64 | _urlencode)"
  780. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  781. _debug3 jwk "$jwk"
  782. JWK_HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  783. JWK_HEADERPLACE_PART1='{"nonce": "'
  784. JWK_HEADERPLACE_PART2='", "alg": "RS256", "jwk": '$jwk'}'
  785. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  786. _debug "EC key"
  787. crv="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  788. _debug3 crv "$crv"
  789. if [ -z "$crv" ]; then
  790. _debug "Let's try ASN1 OID"
  791. crv_oid="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep "^ASN1 OID:" | cut -d ":" -f 2 | tr -d " \r\n")"
  792. _debug3 crv_oid "$crv_oid"
  793. case "${crv_oid}" in
  794. "prime256v1")
  795. crv="P-256"
  796. ;;
  797. "secp384r1")
  798. crv="P-384"
  799. ;;
  800. "secp521r1")
  801. crv="P-521"
  802. ;;
  803. *)
  804. _err "ECC oid : $crv_oid"
  805. return 1
  806. ;;
  807. esac
  808. _debug3 crv "$crv"
  809. fi
  810. pubi="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  811. pubi=$(_math "$pubi" + 1)
  812. _debug3 pubi "$pubi"
  813. pubj="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  814. pubj=$(_math "$pubj" - 1)
  815. _debug3 pubj "$pubj"
  816. pubtext="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  817. _debug3 pubtext "$pubtext"
  818. xlen="$(printf "%s" "$pubtext" | tr -d ':' | wc -c)"
  819. xlen=$(_math "$xlen" / 4)
  820. _debug3 xlen "$xlen"
  821. xend=$(_math "$xlen" + 1)
  822. x="$(printf "%s" "$pubtext" | cut -d : -f 2-"$xend")"
  823. _debug3 x "$x"
  824. x64="$(printf "%s" "$x" | tr -d : | _h2b | _base64 | _urlencode)"
  825. _debug3 x64 "$x64"
  826. xend=$(_math "$xend" + 1)
  827. y="$(printf "%s" "$pubtext" | cut -d : -f "$xend"-10000)"
  828. _debug3 y "$y"
  829. y64="$(printf "%s" "$y" | tr -d : | _h2b | _base64 | _urlencode)"
  830. _debug3 y64 "$y64"
  831. jwk='{"crv": "'$crv'", "kty": "EC", "x": "'$x64'", "y": "'$y64'"}'
  832. _debug3 jwk "$jwk"
  833. JWK_HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  834. JWK_HEADERPLACE_PART1='{"nonce": "'
  835. JWK_HEADERPLACE_PART2='", "alg": "ES256", "jwk": '$jwk'}'
  836. else
  837. _err "Only RSA or EC key is supported."
  838. return 1
  839. fi
  840. _debug3 JWK_HEADER "$JWK_HEADER"
  841. __CACHED_JWK_KEY_FILE="$keyfile"
  842. }
  843. _time() {
  844. date -u "+%s"
  845. }
  846. _mktemp() {
  847. if _exists mktemp; then
  848. if mktemp 2>/dev/null; then
  849. return 0
  850. elif _contains "$(mktemp 2>&1)" "-t prefix" && mktemp -t "$PROJECT_NAME" 2>/dev/null; then
  851. #for Mac osx
  852. return 0
  853. fi
  854. fi
  855. if [ -d "/tmp" ]; then
  856. echo "/tmp/${PROJECT_NAME}wefADf24sf.$(_time).tmp"
  857. return 0
  858. elif [ "$LE_TEMP_DIR" ] && mkdir -p "$LE_TEMP_DIR"; then
  859. echo "/$LE_TEMP_DIR/wefADf24sf.$(_time).tmp"
  860. return 0
  861. fi
  862. _err "Can not create temp file."
  863. }
  864. _inithttp() {
  865. if [ -z "$HTTP_HEADER" ] || ! touch "$HTTP_HEADER"; then
  866. HTTP_HEADER="$(_mktemp)"
  867. _debug2 HTTP_HEADER "$HTTP_HEADER"
  868. fi
  869. if [ "$__HTTP_INITIALIZED" ]; then
  870. if [ "$_ACME_CURL$_ACME_WGET" ]; then
  871. _debug2 "Http already initialized."
  872. return 0
  873. fi
  874. fi
  875. if [ -z "$_ACME_CURL" ] && _exists "curl"; then
  876. _ACME_CURL="curl -L --silent --dump-header $HTTP_HEADER "
  877. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  878. _CURL_DUMP="$(_mktemp)"
  879. _ACME_CURL="$_ACME_CURL --trace-ascii $_CURL_DUMP "
  880. fi
  881. if [ "$CA_BUNDLE" ]; then
  882. _ACME_CURL="$_ACME_CURL --cacert $CA_BUNDLE "
  883. fi
  884. fi
  885. if [ -z "$_ACME_WGET" ] && _exists "wget"; then
  886. _ACME_WGET="wget -q"
  887. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  888. _ACME_WGET="$_ACME_WGET -d "
  889. fi
  890. if [ "$CA_BUNDLE" ]; then
  891. _ACME_WGET="$_ACME_WGET --ca-certificate $CA_BUNDLE "
  892. fi
  893. fi
  894. __HTTP_INITIALIZED=1
  895. }
  896. # body url [needbase64] [POST|PUT]
  897. _post() {
  898. body="$1"
  899. url="$2"
  900. needbase64="$3"
  901. httpmethod="$4"
  902. if [ -z "$httpmethod" ]; then
  903. httpmethod="POST"
  904. fi
  905. _debug $httpmethod
  906. _debug "url" "$url"
  907. _debug2 "body" "$body"
  908. _inithttp
  909. if [ "$_ACME_CURL" ]; then
  910. _CURL="$_ACME_CURL"
  911. if [ "$HTTPS_INSECURE" ]; then
  912. _CURL="$_CURL --insecure "
  913. fi
  914. _debug "_CURL" "$_CURL"
  915. if [ "$needbase64" ]; then
  916. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$url" | _base64)"
  917. else
  918. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$url")"
  919. fi
  920. _ret="$?"
  921. if [ "$_ret" != "0" ]; then
  922. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $_ret"
  923. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  924. _err "Here is the curl dump log:"
  925. _err "$(cat "$_CURL_DUMP")"
  926. fi
  927. fi
  928. elif [ "$_ACME_WGET" ]; then
  929. _WGET="$_ACME_WGET"
  930. if [ "$HTTPS_INSECURE" ]; then
  931. _WGET="$_WGET --no-check-certificate "
  932. fi
  933. _debug "_WGET" "$_WGET"
  934. if [ "$needbase64" ]; then
  935. if [ "$httpmethod" = "POST" ]; then
  936. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  937. else
  938. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  939. fi
  940. else
  941. if [ "$httpmethod" = "POST" ]; then
  942. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER")"
  943. else
  944. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER")"
  945. fi
  946. fi
  947. _ret="$?"
  948. if [ "$_ret" = "8" ]; then
  949. _ret=0
  950. _debug "wget returns 8, the server returns a 'Bad request' respons, lets process the response later."
  951. fi
  952. if [ "$_ret" != "0" ]; then
  953. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $_ret"
  954. fi
  955. _sed_i "s/^ *//g" "$HTTP_HEADER"
  956. else
  957. _ret="$?"
  958. _err "Neither curl nor wget is found, can not do $httpmethod."
  959. fi
  960. _debug "_ret" "$_ret"
  961. printf "%s" "$response"
  962. return $_ret
  963. }
  964. # url getheader timeout
  965. _get() {
  966. _debug GET
  967. url="$1"
  968. onlyheader="$2"
  969. t="$3"
  970. _debug url "$url"
  971. _debug "timeout" "$t"
  972. _inithttp
  973. if [ "$_ACME_CURL" ]; then
  974. _CURL="$_ACME_CURL"
  975. if [ "$HTTPS_INSECURE" ]; then
  976. _CURL="$_CURL --insecure "
  977. fi
  978. if [ "$t" ]; then
  979. _CURL="$_CURL --connect-timeout $t"
  980. fi
  981. _debug "_CURL" "$_CURL"
  982. if [ "$onlyheader" ]; then
  983. $_CURL -I --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
  984. else
  985. $_CURL --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
  986. fi
  987. ret=$?
  988. if [ "$ret" != "0" ]; then
  989. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $ret"
  990. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  991. _err "Here is the curl dump log:"
  992. _err "$(cat "$_CURL_DUMP")"
  993. fi
  994. fi
  995. elif [ "$_ACME_WGET" ]; then
  996. _WGET="$_ACME_WGET"
  997. if [ "$HTTPS_INSECURE" ]; then
  998. _WGET="$_WGET --no-check-certificate "
  999. fi
  1000. if [ "$t" ]; then
  1001. _WGET="$_WGET --timeout=$t"
  1002. fi
  1003. _debug "_WGET" "$_WGET"
  1004. if [ "$onlyheader" ]; then
  1005. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -S -O /dev/null "$url" 2>&1 | sed 's/^[ ]*//g'
  1006. else
  1007. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - "$url"
  1008. fi
  1009. ret=$?
  1010. if [ "$_ret" = "8" ]; then
  1011. _ret=0
  1012. _debug "wget returns 8, the server returns a 'Bad request' respons, lets process the response later."
  1013. fi
  1014. if [ "$ret" != "0" ]; then
  1015. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $ret"
  1016. fi
  1017. else
  1018. ret=$?
  1019. _err "Neither curl nor wget is found, can not do GET."
  1020. fi
  1021. _debug "ret" "$ret"
  1022. return $ret
  1023. }
  1024. _head_n() {
  1025. head -n "$1"
  1026. }
  1027. _tail_n() {
  1028. if ! tail -n "$1" 2>/dev/null; then
  1029. #fix for solaris
  1030. tail -"$1"
  1031. fi
  1032. }
  1033. # url payload needbase64 keyfile
  1034. _send_signed_request() {
  1035. url=$1
  1036. payload=$2
  1037. needbase64=$3
  1038. keyfile=$4
  1039. if [ -z "$keyfile" ]; then
  1040. keyfile="$ACCOUNT_KEY_PATH"
  1041. fi
  1042. _debug url "$url"
  1043. _debug payload "$payload"
  1044. if ! _calcjwk "$keyfile"; then
  1045. return 1
  1046. fi
  1047. payload64=$(printf "%s" "$payload" | _base64 | _urlencode)
  1048. _debug3 payload64 "$payload64"
  1049. if [ -z "$_CACHED_NONCE" ]; then
  1050. _debug2 "Get nonce."
  1051. nonceurl="$API/directory"
  1052. _headers="$(_get "$nonceurl" "onlyheader")"
  1053. if [ "$?" != "0" ]; then
  1054. _err "Can not connect to $nonceurl to get nonce."
  1055. return 1
  1056. fi
  1057. _debug2 _headers "$_headers"
  1058. _CACHED_NONCE="$(echo "$_headers" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1059. _debug2 _CACHED_NONCE "$_CACHED_NONCE"
  1060. else
  1061. _debug2 "Use _CACHED_NONCE" "$_CACHED_NONCE"
  1062. fi
  1063. nonce="$_CACHED_NONCE"
  1064. _debug2 nonce "$nonce"
  1065. protected="$JWK_HEADERPLACE_PART1$nonce$JWK_HEADERPLACE_PART2"
  1066. _debug3 protected "$protected"
  1067. protected64="$(printf "%s" "$protected" | _base64 | _urlencode)"
  1068. _debug3 protected64 "$protected64"
  1069. if ! _sig_t="$(printf "%s" "$protected64.$payload64" | _sign "$keyfile" "sha256")"; then
  1070. _err "Sign request failed."
  1071. return 1
  1072. fi
  1073. _debug3 _sig_t "$_sig_t"
  1074. sig="$(printf "%s" "$_sig_t" | _urlencode)"
  1075. _debug3 sig "$sig"
  1076. body="{\"header\": $JWK_HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  1077. _debug3 body "$body"
  1078. response="$(_post "$body" "$url" "$needbase64")"
  1079. _CACHED_NONCE=""
  1080. if [ "$?" != "0" ]; then
  1081. _err "Can not post to $url"
  1082. return 1
  1083. fi
  1084. _debug2 original "$response"
  1085. response="$(echo "$response" | _normalizeJson)"
  1086. responseHeaders="$(cat "$HTTP_HEADER")"
  1087. _debug2 responseHeaders "$responseHeaders"
  1088. _debug2 response "$response"
  1089. code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n")"
  1090. _debug code "$code"
  1091. _CACHED_NONCE="$(echo "$responseHeaders" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1092. }
  1093. #setopt "file" "opt" "=" "value" [";"]
  1094. _setopt() {
  1095. __conf="$1"
  1096. __opt="$2"
  1097. __sep="$3"
  1098. __val="$4"
  1099. __end="$5"
  1100. if [ -z "$__opt" ]; then
  1101. _usage usage: _setopt '"file" "opt" "=" "value" [";"]'
  1102. return
  1103. fi
  1104. if [ ! -f "$__conf" ]; then
  1105. touch "$__conf"
  1106. fi
  1107. if grep -n "^$__opt$__sep" "$__conf" >/dev/null; then
  1108. _debug3 OK
  1109. if _contains "$__val" "&"; then
  1110. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1111. fi
  1112. text="$(cat "$__conf")"
  1113. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1114. elif grep -n "^#$__opt$__sep" "$__conf" >/dev/null; then
  1115. if _contains "$__val" "&"; then
  1116. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1117. fi
  1118. text="$(cat "$__conf")"
  1119. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1120. else
  1121. _debug3 APP
  1122. echo "$__opt$__sep$__val$__end" >>"$__conf"
  1123. fi
  1124. _debug2 "$(grep -n "^$__opt$__sep" "$__conf")"
  1125. }
  1126. #_save_conf file key value
  1127. #save to conf
  1128. _save_conf() {
  1129. _s_c_f="$1"
  1130. _sdkey="$2"
  1131. _sdvalue="$3"
  1132. if [ "$_s_c_f" ]; then
  1133. _setopt "$_s_c_f" "$_sdkey" "=" "'$_sdvalue'"
  1134. else
  1135. _err "config file is empty, can not save $_sdkey=$_sdvalue"
  1136. fi
  1137. }
  1138. #_clear_conf file key
  1139. _clear_conf() {
  1140. _c_c_f="$1"
  1141. _sdkey="$2"
  1142. if [ "$_c_c_f" ]; then
  1143. _conf_data="$(cat "$_c_c_f")"
  1144. echo "$_conf_data" | sed "s/^$_sdkey *=.*$//" >"$_c_c_f"
  1145. else
  1146. _err "config file is empty, can not clear"
  1147. fi
  1148. }
  1149. #_read_conf file key
  1150. _read_conf() {
  1151. _r_c_f="$1"
  1152. _sdkey="$2"
  1153. if [ -f "$_r_c_f" ]; then
  1154. (
  1155. eval "$(grep "^$_sdkey *=" "$_r_c_f")"
  1156. eval "printf \"%s\" \"\$$_sdkey\""
  1157. )
  1158. else
  1159. _debug "config file is empty, can not read $_sdkey"
  1160. fi
  1161. }
  1162. #_savedomainconf key value
  1163. #save to domain.conf
  1164. _savedomainconf() {
  1165. _save_conf "$DOMAIN_CONF" "$1" "$2"
  1166. }
  1167. #_cleardomainconf key
  1168. _cleardomainconf() {
  1169. _clear_conf "$DOMAIN_CONF" "$1"
  1170. }
  1171. #_readdomainconf key
  1172. _readdomainconf() {
  1173. _read_conf "$DOMAIN_CONF" "$1"
  1174. }
  1175. #_saveaccountconf key value
  1176. _saveaccountconf() {
  1177. _save_conf "$ACCOUNT_CONF_PATH" "$1" "$2"
  1178. }
  1179. #_clearaccountconf key
  1180. _clearaccountconf() {
  1181. _clear_conf "$ACCOUNT_CONF_PATH" "$1"
  1182. }
  1183. #_savecaconf key value
  1184. _savecaconf() {
  1185. _save_conf "$CA_CONF" "$1" "$2"
  1186. }
  1187. #_readcaconf key
  1188. _readcaconf() {
  1189. _read_conf "$CA_CONF" "$1"
  1190. }
  1191. #_clearaccountconf key
  1192. _clearcaconf() {
  1193. _clear_conf "$CA_CONF" "$1"
  1194. }
  1195. # content localaddress
  1196. _startserver() {
  1197. content="$1"
  1198. ncaddr="$2"
  1199. _debug "ncaddr" "$ncaddr"
  1200. _debug "startserver: $$"
  1201. nchelp="$(nc -h 2>&1)"
  1202. _debug Le_HTTPPort "$Le_HTTPPort"
  1203. _debug Le_Listen_V4 "$Le_Listen_V4"
  1204. _debug Le_Listen_V6 "$Le_Listen_V6"
  1205. _NC="nc"
  1206. if [ "$Le_Listen_V4" ]; then
  1207. _NC="$_NC -4"
  1208. elif [ "$Le_Listen_V6" ]; then
  1209. _NC="$_NC -6"
  1210. fi
  1211. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null; then
  1212. _NC="$_NC -q 1 -l $ncaddr"
  1213. else
  1214. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null; then
  1215. _NC="$_NC -c -l $ncaddr"
  1216. elif echo "$nchelp" | grep "\-N" | grep "Shutdown the network socket after EOF on stdin" >/dev/null; then
  1217. _NC="$_NC -N -l $ncaddr"
  1218. else
  1219. _NC="$_NC -l $ncaddr"
  1220. fi
  1221. fi
  1222. _debug "_NC" "$_NC"
  1223. #for centos ncat
  1224. if _contains "$nchelp" "nmap.org"; then
  1225. _debug "Using ncat: nmap.org"
  1226. if ! _exec "printf \"%s\r\n\r\n%s\" \"HTTP/1.1 200 OK\" \"$content\" | $_NC \"$Le_HTTPPort\" >&2"; then
  1227. _exec_err
  1228. return 1
  1229. fi
  1230. if [ "$DEBUG" ]; then
  1231. _exec_err
  1232. fi
  1233. return
  1234. fi
  1235. # while true ; do
  1236. if ! _exec "printf \"%s\r\n\r\n%s\" \"HTTP/1.1 200 OK\" \"$content\" | $_NC -p \"$Le_HTTPPort\" >&2"; then
  1237. _exec "printf \"%s\r\n\r\n%s\" \"HTTP/1.1 200 OK\" \"$content\" | $_NC \"$Le_HTTPPort\" >&2"
  1238. fi
  1239. if [ "$?" != "0" ]; then
  1240. _err "nc listen error."
  1241. _exec_err
  1242. exit 1
  1243. fi
  1244. if [ "$DEBUG" ]; then
  1245. _exec_err
  1246. fi
  1247. # done
  1248. }
  1249. _stopserver() {
  1250. pid="$1"
  1251. _debug "pid" "$pid"
  1252. if [ -z "$pid" ]; then
  1253. return
  1254. fi
  1255. _debug2 "Le_HTTPPort" "$Le_HTTPPort"
  1256. if [ "$Le_HTTPPort" ]; then
  1257. if [ "$DEBUG" ] && [ "$DEBUG" -gt "3" ]; then
  1258. _get "http://localhost:$Le_HTTPPort" "" 1
  1259. else
  1260. _get "http://localhost:$Le_HTTPPort" "" 1 >/dev/null 2>&1
  1261. fi
  1262. fi
  1263. _debug2 "Le_TLSPort" "$Le_TLSPort"
  1264. if [ "$Le_TLSPort" ]; then
  1265. if [ "$DEBUG" ] && [ "$DEBUG" -gt "3" ]; then
  1266. _get "https://localhost:$Le_TLSPort" "" 1
  1267. _get "https://localhost:$Le_TLSPort" "" 1
  1268. else
  1269. _get "https://localhost:$Le_TLSPort" "" 1 >/dev/null 2>&1
  1270. _get "https://localhost:$Le_TLSPort" "" 1 >/dev/null 2>&1
  1271. fi
  1272. fi
  1273. }
  1274. # sleep sec
  1275. _sleep() {
  1276. _sleep_sec="$1"
  1277. if [ "$__INTERACTIVE" ]; then
  1278. _sleep_c="$_sleep_sec"
  1279. while [ "$_sleep_c" -ge "0" ]; do
  1280. printf "\r \r"
  1281. __green "$_sleep_c"
  1282. _sleep_c="$(_math "$_sleep_c" - 1)"
  1283. sleep 1
  1284. done
  1285. printf "\r"
  1286. else
  1287. sleep "$_sleep_sec"
  1288. fi
  1289. }
  1290. # _starttlsserver san_a san_b port content _ncaddr
  1291. _starttlsserver() {
  1292. _info "Starting tls server."
  1293. san_a="$1"
  1294. san_b="$2"
  1295. port="$3"
  1296. content="$4"
  1297. opaddr="$5"
  1298. _debug san_a "$san_a"
  1299. _debug san_b "$san_b"
  1300. _debug port "$port"
  1301. #create key TLS_KEY
  1302. if ! _createkey "2048" "$TLS_KEY"; then
  1303. _err "Create tls validation key error."
  1304. return 1
  1305. fi
  1306. #create csr
  1307. alt="$san_a"
  1308. if [ "$san_b" ]; then
  1309. alt="$alt,$san_b"
  1310. fi
  1311. if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF"; then
  1312. _err "Create tls validation csr error."
  1313. return 1
  1314. fi
  1315. #self signed
  1316. if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT"; then
  1317. _err "Create tls validation cert error."
  1318. return 1
  1319. fi
  1320. __S_OPENSSL="$OPENSSL_BIN s_server -cert $TLS_CERT -key $TLS_KEY "
  1321. if [ "$opaddr" ]; then
  1322. __S_OPENSSL="$__S_OPENSSL -accept $opaddr:$port"
  1323. else
  1324. __S_OPENSSL="$__S_OPENSSL -accept $port"
  1325. fi
  1326. _debug Le_Listen_V4 "$Le_Listen_V4"
  1327. _debug Le_Listen_V6 "$Le_Listen_V6"
  1328. if [ "$Le_Listen_V4" ]; then
  1329. __S_OPENSSL="$__S_OPENSSL -4"
  1330. elif [ "$Le_Listen_V6" ]; then
  1331. __S_OPENSSL="$__S_OPENSSL -6"
  1332. fi
  1333. _debug "$__S_OPENSSL"
  1334. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1335. (printf "%s\r\n\r\n%s" "HTTP/1.1 200 OK" "$content" | $__S_OPENSSL -tlsextdebug) &
  1336. else
  1337. (printf "%s\r\n\r\n%s" "HTTP/1.1 200 OK" "$content" | $__S_OPENSSL >/dev/null 2>&1) &
  1338. fi
  1339. serverproc="$!"
  1340. sleep 1
  1341. _debug serverproc "$serverproc"
  1342. }
  1343. #file
  1344. _readlink() {
  1345. _rf="$1"
  1346. if ! readlink -f "$_rf" 2>/dev/null; then
  1347. if _startswith "$_rf" "\./$PROJECT_ENTRY"; then
  1348. printf -- "%s" "$(pwd)/$PROJECT_ENTRY"
  1349. return 0
  1350. fi
  1351. readlink "$_rf"
  1352. fi
  1353. }
  1354. __initHome() {
  1355. if [ -z "$_SCRIPT_HOME" ]; then
  1356. if _exists readlink && _exists dirname; then
  1357. _debug "Lets find script dir."
  1358. _debug "_SCRIPT_" "$_SCRIPT_"
  1359. _script="$(_readlink "$_SCRIPT_")"
  1360. _debug "_script" "$_script"
  1361. _script_home="$(dirname "$_script")"
  1362. _debug "_script_home" "$_script_home"
  1363. if [ -d "$_script_home" ]; then
  1364. _SCRIPT_HOME="$_script_home"
  1365. else
  1366. _err "It seems the script home is not correct:$_script_home"
  1367. fi
  1368. fi
  1369. fi
  1370. # if [ -z "$LE_WORKING_DIR" ]; then
  1371. # if [ -f "$DEFAULT_INSTALL_HOME/account.conf" ]; then
  1372. # _debug "It seems that $PROJECT_NAME is already installed in $DEFAULT_INSTALL_HOME"
  1373. # LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1374. # else
  1375. # LE_WORKING_DIR="$_SCRIPT_HOME"
  1376. # fi
  1377. # fi
  1378. if [ -z "$LE_WORKING_DIR" ]; then
  1379. _debug "Using default home:$DEFAULT_INSTALL_HOME"
  1380. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1381. fi
  1382. export LE_WORKING_DIR
  1383. _DEFAULT_ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  1384. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1385. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ]; then
  1386. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  1387. fi
  1388. fi
  1389. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1390. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  1391. fi
  1392. DEFAULT_LOG_FILE="$LE_WORKING_DIR/$PROJECT_NAME.log"
  1393. DEFAULT_CA_HOME="$LE_WORKING_DIR/ca"
  1394. if [ -z "$LE_TEMP_DIR" ]; then
  1395. LE_TEMP_DIR="$LE_WORKING_DIR/tmp"
  1396. fi
  1397. }
  1398. #[domain] [keylength]
  1399. _initpath() {
  1400. __initHome
  1401. if [ -f "$ACCOUNT_CONF_PATH" ]; then
  1402. . "$ACCOUNT_CONF_PATH"
  1403. fi
  1404. if [ "$IN_CRON" ]; then
  1405. if [ ! "$_USER_PATH_EXPORTED" ]; then
  1406. _USER_PATH_EXPORTED=1
  1407. export PATH="$USER_PATH:$PATH"
  1408. fi
  1409. fi
  1410. if [ -z "$CA_HOME" ]; then
  1411. CA_HOME="$DEFAULT_CA_HOME"
  1412. fi
  1413. if [ -z "$API" ]; then
  1414. if [ -z "$STAGE" ]; then
  1415. API="$DEFAULT_CA"
  1416. else
  1417. API="$STAGE_CA"
  1418. _info "Using stage api:$API"
  1419. fi
  1420. fi
  1421. _API_HOST="$(echo "$API" | cut -d : -f 2 | tr -d '/')"
  1422. CA_DIR="$CA_HOME/$_API_HOST"
  1423. _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
  1424. if [ -z "$CA_CONF" ]; then
  1425. CA_CONF="$_DEFAULT_CA_CONF"
  1426. fi
  1427. if [ -f "$CA_CONF" ]; then
  1428. . "$CA_CONF"
  1429. fi
  1430. if [ -z "$ACME_DIR" ]; then
  1431. ACME_DIR="/home/.acme"
  1432. fi
  1433. if [ -z "$APACHE_CONF_BACKUP_DIR" ]; then
  1434. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
  1435. fi
  1436. if [ -z "$USER_AGENT" ]; then
  1437. USER_AGENT="$DEFAULT_USER_AGENT"
  1438. fi
  1439. if [ -z "$HTTP_HEADER" ]; then
  1440. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  1441. fi
  1442. _OLD_ACCOUNT_KEY="$LE_WORKING_DIR/account.key"
  1443. _OLD_ACCOUNT_JSON="$LE_WORKING_DIR/account.json"
  1444. _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
  1445. _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
  1446. if [ -z "$ACCOUNT_KEY_PATH" ]; then
  1447. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  1448. fi
  1449. if [ -z "$ACCOUNT_JSON_PATH" ]; then
  1450. ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
  1451. fi
  1452. _DEFAULT_CERT_HOME="$LE_WORKING_DIR"
  1453. if [ -z "$CERT_HOME" ]; then
  1454. CERT_HOME="$_DEFAULT_CERT_HOME"
  1455. fi
  1456. if [ -z "$OPENSSL_BIN" ]; then
  1457. OPENSSL_BIN="$DEFAULT_OPENSSL_BIN"
  1458. fi
  1459. if [ -z "$1" ]; then
  1460. return 0
  1461. fi
  1462. domain="$1"
  1463. _ilength="$2"
  1464. if [ -z "$DOMAIN_PATH" ]; then
  1465. domainhome="$CERT_HOME/$domain"
  1466. domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
  1467. DOMAIN_PATH="$domainhome"
  1468. if _isEccKey "$_ilength"; then
  1469. DOMAIN_PATH="$domainhomeecc"
  1470. else
  1471. if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ]; then
  1472. _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
  1473. fi
  1474. fi
  1475. _debug DOMAIN_PATH "$DOMAIN_PATH"
  1476. fi
  1477. if [ -z "$DOMAIN_CONF" ]; then
  1478. DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
  1479. fi
  1480. if [ -z "$DOMAIN_SSL_CONF" ]; then
  1481. DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
  1482. fi
  1483. if [ -z "$CSR_PATH" ]; then
  1484. CSR_PATH="$DOMAIN_PATH/$domain.csr"
  1485. fi
  1486. if [ -z "$CERT_KEY_PATH" ]; then
  1487. CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
  1488. fi
  1489. if [ -z "$CERT_PATH" ]; then
  1490. CERT_PATH="$DOMAIN_PATH/$domain.cer"
  1491. fi
  1492. if [ -z "$CA_CERT_PATH" ]; then
  1493. CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
  1494. fi
  1495. if [ -z "$CERT_FULLCHAIN_PATH" ]; then
  1496. CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
  1497. fi
  1498. if [ -z "$CERT_PFX_PATH" ]; then
  1499. CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
  1500. fi
  1501. if [ -z "$TLS_CONF" ]; then
  1502. TLS_CONF="$DOMAIN_PATH/tls.valdation.conf"
  1503. fi
  1504. if [ -z "$TLS_CERT" ]; then
  1505. TLS_CERT="$DOMAIN_PATH/tls.valdation.cert"
  1506. fi
  1507. if [ -z "$TLS_KEY" ]; then
  1508. TLS_KEY="$DOMAIN_PATH/tls.valdation.key"
  1509. fi
  1510. if [ -z "$TLS_CSR" ]; then
  1511. TLS_CSR="$DOMAIN_PATH/tls.valdation.csr"
  1512. fi
  1513. }
  1514. _exec() {
  1515. if [ -z "$_EXEC_TEMP_ERR" ]; then
  1516. _EXEC_TEMP_ERR="$(_mktemp)"
  1517. fi
  1518. if [ "$_EXEC_TEMP_ERR" ]; then
  1519. eval "$@ 2>>$_EXEC_TEMP_ERR"
  1520. else
  1521. eval "$@"
  1522. fi
  1523. }
  1524. _exec_err() {
  1525. [ "$_EXEC_TEMP_ERR" ] && _err "$(cat "$_EXEC_TEMP_ERR")" && echo "" >"$_EXEC_TEMP_ERR"
  1526. }
  1527. _apachePath() {
  1528. _APACHECTL="apachectl"
  1529. if ! _exists apachectl; then
  1530. if _exists apache2ctl; then
  1531. _APACHECTL="apache2ctl"
  1532. else
  1533. _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
  1534. _err "Please use webroot mode to try again."
  1535. return 1
  1536. fi
  1537. fi
  1538. if ! _exec $_APACHECTL -V >/dev/null; then
  1539. _exec_err
  1540. return 1
  1541. fi
  1542. if [ "$APACHE_HTTPD_CONF" ]; then
  1543. _saveaccountconf APACHE_HTTPD_CONF "$APACHE_HTTPD_CONF"
  1544. httpdconf="$APACHE_HTTPD_CONF"
  1545. httpdconfname="$(basename "$httpdconfname")"
  1546. else
  1547. httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"')"
  1548. _debug httpdconfname "$httpdconfname"
  1549. if [ -z "$httpdconfname" ]; then
  1550. _err "Can not read apache config file."
  1551. return 1
  1552. fi
  1553. if _startswith "$httpdconfname" '/'; then
  1554. httpdconf="$httpdconfname"
  1555. httpdconfname="$(basename "$httpdconfname")"
  1556. else
  1557. httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"')"
  1558. _debug httpdroot "$httpdroot"
  1559. httpdconf="$httpdroot/$httpdconfname"
  1560. httpdconfname="$(basename "$httpdconfname")"
  1561. fi
  1562. fi
  1563. _debug httpdconf "$httpdconf"
  1564. _debug httpdconfname "$httpdconfname"
  1565. if [ ! -f "$httpdconf" ]; then
  1566. _err "Apache Config file not found" "$httpdconf"
  1567. return 1
  1568. fi
  1569. return 0
  1570. }
  1571. _restoreApache() {
  1572. if [ -z "$usingApache" ]; then
  1573. return 0
  1574. fi
  1575. _initpath
  1576. if ! _apachePath; then
  1577. return 1
  1578. fi
  1579. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ]; then
  1580. _debug "No config file to restore."
  1581. return 0
  1582. fi
  1583. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" >"$httpdconf"
  1584. _debug "Restored: $httpdconf."
  1585. if ! _exec $_APACHECTL -t; then
  1586. _exec_err
  1587. _err "Sorry, restore apache config error, please contact me."
  1588. return 1
  1589. fi
  1590. _debug "Restored successfully."
  1591. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1592. return 0
  1593. }
  1594. _setApache() {
  1595. _initpath
  1596. if ! _apachePath; then
  1597. return 1
  1598. fi
  1599. #test the conf first
  1600. _info "Checking if there is an error in the apache config file before starting."
  1601. if ! _exec "$_APACHECTL" -t >/dev/null; then
  1602. _exec_err
  1603. _err "The apache config file has error, please fix it first, then try again."
  1604. _err "Don't worry, there is nothing changed to your system."
  1605. return 1
  1606. else
  1607. _info "OK"
  1608. fi
  1609. #backup the conf
  1610. _debug "Backup apache config file" "$httpdconf"
  1611. if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/"; then
  1612. _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
  1613. _err "This might be a bug of $PROJECT_NAME , pleae report issue: $PROJECT"
  1614. return 1
  1615. fi
  1616. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1617. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  1618. _info "The backup file will be deleted on sucess, just forget it."
  1619. #add alias
  1620. apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2)"
  1621. _debug "apacheVer" "$apacheVer"
  1622. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  1623. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  1624. if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ]; then
  1625. echo "
  1626. Alias /.well-known/acme-challenge $ACME_DIR
  1627. <Directory $ACME_DIR >
  1628. Require all granted
  1629. </Directory>
  1630. " >>"$httpdconf"
  1631. else
  1632. echo "
  1633. Alias /.well-known/acme-challenge $ACME_DIR
  1634. <Directory $ACME_DIR >
  1635. Order allow,deny
  1636. Allow from all
  1637. </Directory>
  1638. " >>"$httpdconf"
  1639. fi
  1640. _msg="$($_APACHECTL -t 2>&1)"
  1641. if [ "$?" != "0" ]; then
  1642. _err "Sorry, apache config error"
  1643. if _restoreApache; then
  1644. _err "The apache config file is restored."
  1645. else
  1646. _err "Sorry, The apache config file can not be restored, please report bug."
  1647. fi
  1648. return 1
  1649. fi
  1650. if [ ! -d "$ACME_DIR" ]; then
  1651. mkdir -p "$ACME_DIR"
  1652. chmod 755 "$ACME_DIR"
  1653. fi
  1654. if ! _exec "$_APACHECTL" graceful; then
  1655. _exec_err
  1656. _err "$_APACHECTL graceful error, please contact me."
  1657. _restoreApache
  1658. return 1
  1659. fi
  1660. usingApache="1"
  1661. return 0
  1662. }
  1663. _clearup() {
  1664. _stopserver "$serverproc"
  1665. serverproc=""
  1666. _restoreApache
  1667. _clearupdns
  1668. if [ -z "$DEBUG" ]; then
  1669. rm -f "$TLS_CONF"
  1670. rm -f "$TLS_CERT"
  1671. rm -f "$TLS_KEY"
  1672. rm -f "$TLS_CSR"
  1673. fi
  1674. }
  1675. _clearupdns() {
  1676. _debug "_clearupdns"
  1677. if [ "$dnsadded" != 1 ] || [ -z "$vlist" ]; then
  1678. _debug "Dns not added, skip."
  1679. return
  1680. fi
  1681. ventries=$(echo "$vlist" | tr ',' ' ')
  1682. for ventry in $ventries; do
  1683. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  1684. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  1685. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  1686. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  1687. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  1688. _info "$d is already verified, skip $vtype."
  1689. continue
  1690. fi
  1691. if [ "$vtype" != "$VTYPE_DNS" ]; then
  1692. _info "Skip $d for $vtype"
  1693. continue
  1694. fi
  1695. d_api="$(_findHook "$d" dnsapi "$_currentRoot")"
  1696. _debug d_api "$d_api"
  1697. if [ -z "$d_api" ]; then
  1698. _info "Not Found domain api file: $d_api"
  1699. continue
  1700. fi
  1701. (
  1702. if ! . "$d_api"; then
  1703. _err "Load file $d_api error. Please check your api file and try again."
  1704. return 1
  1705. fi
  1706. rmcommand="${_currentRoot}_rm"
  1707. if ! _exists "$rmcommand"; then
  1708. _err "It seems that your api file doesn't define $rmcommand"
  1709. return 1
  1710. fi
  1711. txtdomain="_acme-challenge.$d"
  1712. if ! $rmcommand "$txtdomain"; then
  1713. _err "Error removing txt for domain:$txtdomain"
  1714. return 1
  1715. fi
  1716. )
  1717. done
  1718. }
  1719. # webroot removelevel tokenfile
  1720. _clearupwebbroot() {
  1721. __webroot="$1"
  1722. if [ -z "$__webroot" ]; then
  1723. _debug "no webroot specified, skip"
  1724. return 0
  1725. fi
  1726. _rmpath=""
  1727. if [ "$2" = '1' ]; then
  1728. _rmpath="$__webroot/.well-known"
  1729. elif [ "$2" = '2' ]; then
  1730. _rmpath="$__webroot/.well-known/acme-challenge"
  1731. elif [ "$2" = '3' ]; then
  1732. _rmpath="$__webroot/.well-known/acme-challenge/$3"
  1733. else
  1734. _debug "Skip for removelevel:$2"
  1735. fi
  1736. if [ "$_rmpath" ]; then
  1737. if [ "$DEBUG" ]; then
  1738. _debug "Debugging, skip removing: $_rmpath"
  1739. else
  1740. rm -rf "$_rmpath"
  1741. fi
  1742. fi
  1743. return 0
  1744. }
  1745. _on_before_issue() {
  1746. _debug _on_before_issue
  1747. if _hasfield "$Le_Webroot" "$NO_VALUE"; then
  1748. if ! _exists "nc"; then
  1749. _err "Please install netcat(nc) tools first."
  1750. return 1
  1751. fi
  1752. fi
  1753. _debug Le_LocalAddress "$Le_LocalAddress"
  1754. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ')
  1755. _index=1
  1756. _currentRoot=""
  1757. _addrIndex=1
  1758. for d in $alldomains; do
  1759. _debug "Check for domain" "$d"
  1760. _currentRoot="$(_getfield "$Le_Webroot" $_index)"
  1761. _debug "_currentRoot" "$_currentRoot"
  1762. _index=$(_math $_index + 1)
  1763. _checkport=""
  1764. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  1765. _info "Standalone mode."
  1766. if [ -z "$Le_HTTPPort" ]; then
  1767. Le_HTTPPort=80
  1768. else
  1769. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  1770. fi
  1771. _checkport="$Le_HTTPPort"
  1772. elif [ "$_currentRoot" = "$W_TLS" ]; then
  1773. _info "Standalone tls mode."
  1774. if [ -z "$Le_TLSPort" ]; then
  1775. Le_TLSPort=443
  1776. else
  1777. _savedomainconf "Le_TLSPort" "$Le_TLSPort"
  1778. fi
  1779. _checkport="$Le_TLSPort"
  1780. fi
  1781. if [ "$_checkport" ]; then
  1782. _debug _checkport "$_checkport"
  1783. _checkaddr="$(_getfield "$Le_LocalAddress" $_addrIndex)"
  1784. _debug _checkaddr "$_checkaddr"
  1785. _addrIndex="$(_math $_addrIndex + 1)"
  1786. _netprc="$(_ss "$_checkport" | grep "$_checkport")"
  1787. netprc="$(echo "$_netprc" | grep "$_checkaddr")"
  1788. if [ -z "$netprc" ]; then
  1789. netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS")"
  1790. fi
  1791. if [ "$netprc" ]; then
  1792. _err "$netprc"
  1793. _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
  1794. _err "Please stop it first"
  1795. return 1
  1796. fi
  1797. fi
  1798. done
  1799. if _hasfield "$Le_Webroot" "apache"; then
  1800. if ! _setApache; then
  1801. _err "set up apache error. Report error to me."
  1802. return 1
  1803. fi
  1804. else
  1805. usingApache=""
  1806. fi
  1807. #run pre hook
  1808. if [ "$Le_PreHook" ]; then
  1809. _info "Run pre hook:'$Le_PreHook'"
  1810. if ! (
  1811. cd "$DOMAIN_PATH" && eval "$Le_PreHook"
  1812. ); then
  1813. _err "Error when run pre hook."
  1814. return 1
  1815. fi
  1816. fi
  1817. }
  1818. _on_issue_err() {
  1819. _debug _on_issue_err
  1820. if [ "$LOG_FILE" ]; then
  1821. _err "Please check log file for more details: $LOG_FILE"
  1822. else
  1823. _err "Please add '--debug' or '--log' to check more details."
  1824. _err "See: $_DEBUG_WIKI"
  1825. fi
  1826. if [ "$DEBUG" ] && [ "$DEBUG" -gt "0" ]; then
  1827. _debug "$(_dlg_versions)"
  1828. fi
  1829. #run the post hook
  1830. if [ "$Le_PostHook" ]; then
  1831. _info "Run post hook:'$Le_PostHook'"
  1832. if ! (
  1833. cd "$DOMAIN_PATH" && eval "$Le_PostHook"
  1834. ); then
  1835. _err "Error when run post hook."
  1836. return 1
  1837. fi
  1838. fi
  1839. }
  1840. _on_issue_success() {
  1841. _debug _on_issue_success
  1842. #run the post hook
  1843. if [ "$Le_PostHook" ]; then
  1844. _info "Run post hook:'$Le_PostHook'"
  1845. if ! (
  1846. cd "$DOMAIN_PATH" && eval "$Le_PostHook"
  1847. ); then
  1848. _err "Error when run post hook."
  1849. return 1
  1850. fi
  1851. fi
  1852. #run renew hook
  1853. if [ "$IS_RENEW" ] && [ "$Le_RenewHook" ]; then
  1854. _info "Run renew hook:'$Le_RenewHook'"
  1855. if ! (
  1856. cd "$DOMAIN_PATH" && eval "$Le_RenewHook"
  1857. ); then
  1858. _err "Error when run renew hook."
  1859. return 1
  1860. fi
  1861. fi
  1862. }
  1863. updateaccount() {
  1864. _initpath
  1865. _regAccount
  1866. }
  1867. registeraccount() {
  1868. _reg_length="$1"
  1869. _initpath
  1870. _regAccount "$_reg_length"
  1871. }
  1872. __calcAccountKeyHash() {
  1873. [ -f "$ACCOUNT_KEY_PATH" ] && _digest sha256 <"$ACCOUNT_KEY_PATH"
  1874. }
  1875. #keylength
  1876. _regAccount() {
  1877. _initpath
  1878. _reg_length="$1"
  1879. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  1880. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  1881. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  1882. fi
  1883. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  1884. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  1885. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  1886. fi
  1887. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  1888. if ! _create_account_key "$_reg_length"; then
  1889. _err "Create account key error."
  1890. return 1
  1891. fi
  1892. fi
  1893. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  1894. return 1
  1895. fi
  1896. _updateTos=""
  1897. _reg_res="new-reg"
  1898. while true; do
  1899. _debug AGREEMENT "$AGREEMENT"
  1900. regjson='{"resource": "'$_reg_res'", "agreement": "'$AGREEMENT'"}'
  1901. if [ "$ACCOUNT_EMAIL" ]; then
  1902. regjson='{"resource": "'$_reg_res'", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  1903. fi
  1904. if [ -z "$_updateTos" ]; then
  1905. _info "Registering account"
  1906. if ! _send_signed_request "$API/acme/new-reg" "$regjson"; then
  1907. _err "Register account Error: $response"
  1908. return 1
  1909. fi
  1910. if [ "$code" = "" ] || [ "$code" = '201' ]; then
  1911. echo "$response" >"$ACCOUNT_JSON_PATH"
  1912. _info "Registered"
  1913. elif [ "$code" = '409' ]; then
  1914. _info "Already registered"
  1915. else
  1916. _err "Register account Error: $response"
  1917. return 1
  1918. fi
  1919. _accUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  1920. _debug "_accUri" "$_accUri"
  1921. _tos="$(echo "$responseHeaders" | grep "^Link:.*rel=\"terms-of-service\"" | _head_n 1 | _egrep_o "<.*>" | tr -d '<>')"
  1922. _debug "_tos" "$_tos"
  1923. if [ -z "$_tos" ]; then
  1924. _debug "Use default tos: $DEFAULT_AGREEMENT"
  1925. _tos="$DEFAULT_AGREEMENT"
  1926. fi
  1927. if [ "$_tos" != "$AGREEMENT" ]; then
  1928. _updateTos=1
  1929. AGREEMENT="$_tos"
  1930. _reg_res="reg"
  1931. continue
  1932. fi
  1933. else
  1934. _debug "Update tos: $_tos"
  1935. if ! _send_signed_request "$_accUri" "$regjson"; then
  1936. _err "Update tos error."
  1937. return 1
  1938. fi
  1939. if [ "$code" = '202' ]; then
  1940. _info "Update success."
  1941. CA_KEY_HASH="$(__calcAccountKeyHash)"
  1942. _debug "Calc CA_KEY_HASH" "$CA_KEY_HASH"
  1943. _savecaconf CA_KEY_HASH "$CA_KEY_HASH"
  1944. else
  1945. _err "Update account error."
  1946. return 1
  1947. fi
  1948. fi
  1949. return 0
  1950. done
  1951. }
  1952. # domain folder file
  1953. _findHook() {
  1954. _hookdomain="$1"
  1955. _hookcat="$2"
  1956. _hookname="$3"
  1957. if [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname" ]; then
  1958. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname"
  1959. elif [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname.sh" ]; then
  1960. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname.sh"
  1961. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname" ]; then
  1962. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname"
  1963. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname.sh" ]; then
  1964. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname.sh"
  1965. elif [ -f "$LE_WORKING_DIR/$_hookname" ]; then
  1966. d_api="$LE_WORKING_DIR/$_hookname"
  1967. elif [ -f "$LE_WORKING_DIR/$_hookname.sh" ]; then
  1968. d_api="$LE_WORKING_DIR/$_hookname.sh"
  1969. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname" ]; then
  1970. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname"
  1971. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname.sh" ]; then
  1972. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname.sh"
  1973. fi
  1974. printf "%s" "$d_api"
  1975. }
  1976. #domain
  1977. __get_domain_new_authz() {
  1978. _gdnd="$1"
  1979. _info "Getting new-authz for domain" "$_gdnd"
  1980. _Max_new_authz_retry_times=5
  1981. _authz_i=0
  1982. while [ "$_authz_i" -lt "$_Max_new_authz_retry_times" ]; do
  1983. _debug "Try new-authz for the $_authz_i time."
  1984. if ! _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$(_idn "$_gdnd")\"}}"; then
  1985. _err "Can not get domain new authz."
  1986. return 1
  1987. fi
  1988. if ! _contains "$response" "An error occurred while processing your request"; then
  1989. _info "The new-authz request is ok."
  1990. break
  1991. fi
  1992. _authz_i="$(_math "$_authz_i" + 1)"
  1993. _info "The server is busy, Sleep $_authz_i to retry."
  1994. _sleep "$_authz_i"
  1995. done
  1996. if [ "$_authz_i" = "$_Max_new_authz_retry_times" ]; then
  1997. _err "new-authz retry reach the max $_Max_new_authz_retry_times times."
  1998. fi
  1999. if [ ! -z "$code" ] && [ ! "$code" = '201' ]; then
  2000. _err "new-authz error: $response"
  2001. return 1
  2002. fi
  2003. }
  2004. #webroot, domain domainlist keylength
  2005. issue() {
  2006. if [ -z "$2" ]; then
  2007. _usage "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  2008. return 1
  2009. fi
  2010. Le_Webroot="$1"
  2011. Le_Domain="$2"
  2012. Le_Alt="$3"
  2013. Le_Keylength="$4"
  2014. Le_RealCertPath="$5"
  2015. Le_RealKeyPath="$6"
  2016. Le_RealCACertPath="$7"
  2017. Le_ReloadCmd="$8"
  2018. Le_RealFullChainPath="$9"
  2019. Le_PreHook="${10}"
  2020. Le_PostHook="${11}"
  2021. Le_RenewHook="${12}"
  2022. Le_LocalAddress="${13}"
  2023. #remove these later.
  2024. if [ "$Le_Webroot" = "dns-cf" ]; then
  2025. Le_Webroot="dns_cf"
  2026. fi
  2027. if [ "$Le_Webroot" = "dns-dp" ]; then
  2028. Le_Webroot="dns_dp"
  2029. fi
  2030. if [ "$Le_Webroot" = "dns-cx" ]; then
  2031. Le_Webroot="dns_cx"
  2032. fi
  2033. _debug "Using api: $API"
  2034. if [ ! "$IS_RENEW" ]; then
  2035. _initpath "$Le_Domain" "$Le_Keylength"
  2036. mkdir -p "$DOMAIN_PATH"
  2037. fi
  2038. if [ -f "$DOMAIN_CONF" ]; then
  2039. Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
  2040. _debug Le_NextRenewTime "$Le_NextRenewTime"
  2041. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  2042. _saved_domain=$(_readdomainconf Le_Domain)
  2043. _debug _saved_domain "$_saved_domain"
  2044. _saved_alt=$(_readdomainconf Le_Alt)
  2045. _debug _saved_alt "$_saved_alt"
  2046. if [ "$_saved_domain,$_saved_alt" = "$Le_Domain,$Le_Alt" ]; then
  2047. _info "Domains not changed."
  2048. _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
  2049. _info "Add '$(__red '--force')' to force to renew."
  2050. return $RENEW_SKIP
  2051. else
  2052. _info "Domains have changed."
  2053. fi
  2054. fi
  2055. fi
  2056. _savedomainconf "Le_Domain" "$Le_Domain"
  2057. _savedomainconf "Le_Alt" "$Le_Alt"
  2058. _savedomainconf "Le_Webroot" "$Le_Webroot"
  2059. _savedomainconf "Le_PreHook" "$Le_PreHook"
  2060. _savedomainconf "Le_PostHook" "$Le_PostHook"
  2061. _savedomainconf "Le_RenewHook" "$Le_RenewHook"
  2062. if [ "$Le_LocalAddress" ]; then
  2063. _savedomainconf "Le_LocalAddress" "$Le_LocalAddress"
  2064. else
  2065. _cleardomainconf "Le_LocalAddress"
  2066. fi
  2067. Le_API="$API"
  2068. _savedomainconf "Le_API" "$Le_API"
  2069. if [ "$Le_Alt" = "$NO_VALUE" ]; then
  2070. Le_Alt=""
  2071. fi
  2072. if [ "$Le_Keylength" = "$NO_VALUE" ]; then
  2073. Le_Keylength=""
  2074. fi
  2075. if ! _on_before_issue; then
  2076. _err "_on_before_issue."
  2077. return 1
  2078. fi
  2079. _saved_account_key_hash="$(_readcaconf "CA_KEY_HASH")"
  2080. _debug2 _saved_account_key_hash "$_saved_account_key_hash"
  2081. if [ -z "$_saved_account_key_hash" ] || [ "$_saved_account_key_hash" != "$(__calcAccountKeyHash)" ]; then
  2082. if ! _regAccount "$_accountkeylength"; then
  2083. _on_issue_err
  2084. return 1
  2085. fi
  2086. else
  2087. _debug "_saved_account_key_hash is not changed, skip register account."
  2088. fi
  2089. if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ]; then
  2090. _info "Signing from existing CSR."
  2091. else
  2092. _key=$(_readdomainconf Le_Keylength)
  2093. _debug "Read key length:$_key"
  2094. if [ ! -f "$CERT_KEY_PATH" ] || [ "$Le_Keylength" != "$_key" ]; then
  2095. if ! createDomainKey "$Le_Domain" "$Le_Keylength"; then
  2096. _err "Create domain key error."
  2097. _clearup
  2098. _on_issue_err
  2099. return 1
  2100. fi
  2101. fi
  2102. if ! _createcsr "$Le_Domain" "$Le_Alt" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"; then
  2103. _err "Create CSR error."
  2104. _clearup
  2105. _on_issue_err
  2106. return 1
  2107. fi
  2108. fi
  2109. _savedomainconf "Le_Keylength" "$Le_Keylength"
  2110. vlist="$Le_Vlist"
  2111. _info "Getting domain auth token for each domain"
  2112. sep='#'
  2113. if [ -z "$vlist" ]; then
  2114. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ')
  2115. _index=1
  2116. _currentRoot=""
  2117. for d in $alldomains; do
  2118. _info "Getting webroot for domain" "$d"
  2119. _w="$(echo $Le_Webroot | cut -d , -f $_index)"
  2120. _info _w "$_w"
  2121. if [ "$_w" ]; then
  2122. _currentRoot="$_w"
  2123. fi
  2124. _debug "_currentRoot" "$_currentRoot"
  2125. _index=$(_math $_index + 1)
  2126. vtype="$VTYPE_HTTP"
  2127. if _startswith "$_currentRoot" "dns"; then
  2128. vtype="$VTYPE_DNS"
  2129. fi
  2130. if [ "$_currentRoot" = "$W_TLS" ]; then
  2131. vtype="$VTYPE_TLS"
  2132. fi
  2133. if ! __get_domain_new_authz "$d"; then
  2134. _clearup
  2135. _on_issue_err
  2136. return 1
  2137. fi
  2138. if [ -z "$thumbprint" ]; then
  2139. accountkey_json=$(printf "%s" "$jwk" | tr -d ' ')
  2140. thumbprint=$(printf "%s" "$accountkey_json" | _digest "sha256" | _urlencode)
  2141. fi
  2142. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  2143. _debug entry "$entry"
  2144. if [ -z "$entry" ]; then
  2145. _err "Error, can not get domain token $d"
  2146. _clearup
  2147. _on_issue_err
  2148. return 1
  2149. fi
  2150. token="$(printf "%s\n" "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  2151. _debug token "$token"
  2152. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*' | cut -d : -f 2,3 | tr -d '"')"
  2153. _debug uri "$uri"
  2154. keyauthorization="$token.$thumbprint"
  2155. _debug keyauthorization "$keyauthorization"
  2156. if printf "%s" "$response" | grep '"status":"valid"' >/dev/null 2>&1; then
  2157. _info "$d is already verified, skip."
  2158. keyauthorization="$STATE_VERIFIED"
  2159. _debug keyauthorization "$keyauthorization"
  2160. fi
  2161. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  2162. _debug dvlist "$dvlist"
  2163. vlist="$vlist$dvlist,"
  2164. done
  2165. #add entry
  2166. dnsadded=""
  2167. ventries=$(echo "$vlist" | tr ',' ' ')
  2168. for ventry in $ventries; do
  2169. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2170. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2171. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2172. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2173. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  2174. _info "$d is already verified, skip $vtype."
  2175. continue
  2176. fi
  2177. if [ "$vtype" = "$VTYPE_DNS" ]; then
  2178. dnsadded='0'
  2179. txtdomain="_acme-challenge.$d"
  2180. _debug txtdomain "$txtdomain"
  2181. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _urlencode)"
  2182. _debug txt "$txt"
  2183. d_api="$(_findHook "$d" dnsapi "$_currentRoot")"
  2184. _debug d_api "$d_api"
  2185. if [ "$d_api" ]; then
  2186. _info "Found domain api file: $d_api"
  2187. else
  2188. _err "Add the following TXT record:"
  2189. _err "Domain: '$(__green "$txtdomain")'"
  2190. _err "TXT value: '$(__green "$txt")'"
  2191. _err "Please be aware that you prepend _acme-challenge. before your domain"
  2192. _err "so the resulting subdomain will be: $txtdomain"
  2193. continue
  2194. fi
  2195. (
  2196. if ! . "$d_api"; then
  2197. _err "Load file $d_api error. Please check your api file and try again."
  2198. return 1
  2199. fi
  2200. addcommand="${_currentRoot}_add"
  2201. if ! _exists "$addcommand"; then
  2202. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  2203. return 1
  2204. fi
  2205. if ! $addcommand "$txtdomain" "$txt"; then
  2206. _err "Error add txt for domain:$txtdomain"
  2207. return 1
  2208. fi
  2209. )
  2210. if [ "$?" != "0" ]; then
  2211. _clearup
  2212. _on_issue_err
  2213. return 1
  2214. fi
  2215. dnsadded='1'
  2216. fi
  2217. done
  2218. if [ "$dnsadded" = '0' ]; then
  2219. _savedomainconf "Le_Vlist" "$vlist"
  2220. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  2221. _err "Please add the TXT records to the domains, and retry again."
  2222. _clearup
  2223. _on_issue_err
  2224. return 1
  2225. fi
  2226. fi
  2227. if [ "$dnsadded" = '1' ]; then
  2228. if [ -z "$Le_DNSSleep" ]; then
  2229. Le_DNSSleep="$DEFAULT_DNS_SLEEP"
  2230. else
  2231. _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
  2232. fi
  2233. _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
  2234. _sleep "$Le_DNSSleep"
  2235. fi
  2236. _debug "ok, let's start to verify"
  2237. _ncIndex=1
  2238. ventries=$(echo "$vlist" | tr ',' ' ')
  2239. for ventry in $ventries; do
  2240. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2241. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2242. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  2243. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2244. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2245. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  2246. _info "$d is already verified, skip $vtype."
  2247. continue
  2248. fi
  2249. _info "Verifying:$d"
  2250. _debug "d" "$d"
  2251. _debug "keyauthorization" "$keyauthorization"
  2252. _debug "uri" "$uri"
  2253. removelevel=""
  2254. token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
  2255. _debug "_currentRoot" "$_currentRoot"
  2256. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  2257. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  2258. _info "Standalone mode server"
  2259. _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex")"
  2260. _ncIndex="$(_math $_ncIndex + 1)"
  2261. _startserver "$keyauthorization" "$_ncaddr" &
  2262. if [ "$?" != "0" ]; then
  2263. _clearup
  2264. _on_issue_err
  2265. return 1
  2266. fi
  2267. serverproc="$!"
  2268. sleep 1
  2269. _debug serverproc "$serverproc"
  2270. else
  2271. if [ "$_currentRoot" = "apache" ]; then
  2272. wellknown_path="$ACME_DIR"
  2273. else
  2274. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  2275. if [ ! -d "$_currentRoot/.well-known" ]; then
  2276. removelevel='1'
  2277. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ]; then
  2278. removelevel='2'
  2279. else
  2280. removelevel='3'
  2281. fi
  2282. fi
  2283. _debug wellknown_path "$wellknown_path"
  2284. _debug "writing token:$token to $wellknown_path/$token"
  2285. mkdir -p "$wellknown_path"
  2286. if ! printf "%s" "$keyauthorization" >"$wellknown_path/$token"; then
  2287. _err "$d:Can not write token to file : $wellknown_path/$token"
  2288. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2289. _clearup
  2290. _on_issue_err
  2291. return 1
  2292. fi
  2293. if [ ! "$usingApache" ]; then
  2294. if webroot_owner=$(_stat "$_currentRoot"); then
  2295. _debug "Changing owner/group of .well-known to $webroot_owner"
  2296. chown -R "$webroot_owner" "$_currentRoot/.well-known"
  2297. else
  2298. _debug "not chaning owner/group of webroot"
  2299. fi
  2300. fi
  2301. fi
  2302. elif [ "$vtype" = "$VTYPE_TLS" ]; then
  2303. #create A
  2304. #_hash_A="$(printf "%s" $token | _digest "sha256" "hex" )"
  2305. #_debug2 _hash_A "$_hash_A"
  2306. #_x="$(echo $_hash_A | cut -c 1-32)"
  2307. #_debug2 _x "$_x"
  2308. #_y="$(echo $_hash_A | cut -c 33-64)"
  2309. #_debug2 _y "$_y"
  2310. #_SAN_A="$_x.$_y.token.acme.invalid"
  2311. #_debug2 _SAN_A "$_SAN_A"
  2312. #create B
  2313. _hash_B="$(printf "%s" "$keyauthorization" | _digest "sha256" "hex")"
  2314. _debug2 _hash_B "$_hash_B"
  2315. _x="$(echo "$_hash_B" | cut -c 1-32)"
  2316. _debug2 _x "$_x"
  2317. _y="$(echo "$_hash_B" | cut -c 33-64)"
  2318. _debug2 _y "$_y"
  2319. #_SAN_B="$_x.$_y.ka.acme.invalid"
  2320. _SAN_B="$_x.$_y.acme.invalid"
  2321. _debug2 _SAN_B "$_SAN_B"
  2322. _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex")"
  2323. _ncIndex="$(_math "$_ncIndex" + 1)"
  2324. if ! _starttlsserver "$_SAN_B" "$_SAN_A" "$Le_TLSPort" "$keyauthorization" "$_ncaddr"; then
  2325. _err "Start tls server error."
  2326. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2327. _clearup
  2328. _on_issue_err
  2329. return 1
  2330. fi
  2331. fi
  2332. if ! _send_signed_request "$uri" "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"; then
  2333. _err "$d:Can not get challenge: $response"
  2334. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2335. _clearup
  2336. _on_issue_err
  2337. return 1
  2338. fi
  2339. if [ ! -z "$code" ] && [ ! "$code" = '202' ]; then
  2340. _err "$d:Challenge error: $response"
  2341. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2342. _clearup
  2343. _on_issue_err
  2344. return 1
  2345. fi
  2346. waittimes=0
  2347. if [ -z "$MAX_RETRY_TIMES" ]; then
  2348. MAX_RETRY_TIMES=30
  2349. fi
  2350. while true; do
  2351. waittimes=$(_math "$waittimes" + 1)
  2352. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ]; then
  2353. _err "$d:Timeout"
  2354. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2355. _clearup
  2356. _on_issue_err
  2357. return 1
  2358. fi
  2359. _debug "sleep 2 secs to verify"
  2360. sleep 2
  2361. _debug "checking"
  2362. response="$(_get "$uri")"
  2363. if [ "$?" != "0" ]; then
  2364. _err "$d:Verify error:$response"
  2365. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2366. _clearup
  2367. _on_issue_err
  2368. return 1
  2369. fi
  2370. _debug2 original "$response"
  2371. response="$(echo "$response" | _normalizeJson)"
  2372. _debug2 response "$response"
  2373. status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  2374. if [ "$status" = "valid" ]; then
  2375. _info "$(__green Success)"
  2376. _stopserver "$serverproc"
  2377. serverproc=""
  2378. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2379. break
  2380. fi
  2381. if [ "$status" = "invalid" ]; then
  2382. error="$(echo "$response" | tr -d "\r\n" | _egrep_o '"error":\{[^\}]*')"
  2383. _debug2 error "$error"
  2384. errordetail="$(echo "$error" | _egrep_o '"detail": *"[^"]*' | cut -d '"' -f 4)"
  2385. _debug2 errordetail "$errordetail"
  2386. if [ "$errordetail" ]; then
  2387. _err "$d:Verify error:$errordetail"
  2388. else
  2389. _err "$d:Verify error:$error"
  2390. fi
  2391. if [ "$DEBUG" ]; then
  2392. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  2393. _debug "Debug: get token url."
  2394. _get "http://$d/.well-known/acme-challenge/$token" "" 1
  2395. fi
  2396. fi
  2397. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2398. _clearup
  2399. _on_issue_err
  2400. return 1
  2401. fi
  2402. if [ "$status" = "pending" ]; then
  2403. _info "Pending"
  2404. else
  2405. _err "$d:Verify error:$response"
  2406. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2407. _clearup
  2408. _on_issue_err
  2409. return 1
  2410. fi
  2411. done
  2412. done
  2413. _clearup
  2414. _info "Verify finished, start to sign."
  2415. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  2416. if ! _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"; then
  2417. _err "Sign failed."
  2418. _on_issue_err
  2419. return 1
  2420. fi
  2421. _rcert="$response"
  2422. Le_LinkCert="$(grep -i '^Location.*$' "$HTTP_HEADER" | _head_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  2423. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  2424. if [ "$Le_LinkCert" ]; then
  2425. echo "$BEGIN_CERT" >"$CERT_PATH"
  2426. #if ! _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH" ; then
  2427. # _debug "Get cert failed. Let's try last response."
  2428. # printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >> "$CERT_PATH"
  2429. #fi
  2430. if ! printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >>"$CERT_PATH"; then
  2431. _debug "Try cert link."
  2432. _get "$Le_LinkCert" | _base64 "multiline" >>"$CERT_PATH"
  2433. fi
  2434. echo "$END_CERT" >>"$CERT_PATH"
  2435. _info "$(__green "Cert success.")"
  2436. cat "$CERT_PATH"
  2437. _info "Your cert is in $(__green " $CERT_PATH ")"
  2438. if [ -f "$CERT_KEY_PATH" ]; then
  2439. _info "Your cert key is in $(__green " $CERT_KEY_PATH ")"
  2440. fi
  2441. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  2442. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ]; then
  2443. USER_PATH="$PATH"
  2444. _saveaccountconf "USER_PATH" "$USER_PATH"
  2445. fi
  2446. fi
  2447. if [ -z "$Le_LinkCert" ]; then
  2448. response="$(echo "$response" | _dbase64 "multiline" | _normalizeJson)"
  2449. _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
  2450. _on_issue_err
  2451. return 1
  2452. fi
  2453. _cleardomainconf "Le_Vlist"
  2454. Le_LinkIssuer=$(grep -i '^Link' "$HTTP_HEADER" | _head_n 1 | cut -d " " -f 2 | cut -d ';' -f 1 | tr -d '<>')
  2455. if ! _contains "$Le_LinkIssuer" ":"; then
  2456. Le_LinkIssuer="$API$Le_LinkIssuer"
  2457. fi
  2458. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  2459. if [ "$Le_LinkIssuer" ]; then
  2460. echo "$BEGIN_CERT" >"$CA_CERT_PATH"
  2461. _get "$Le_LinkIssuer" | _base64 "multiline" >>"$CA_CERT_PATH"
  2462. echo "$END_CERT" >>"$CA_CERT_PATH"
  2463. _info "The intermediate CA cert is in $(__green " $CA_CERT_PATH ")"
  2464. cat "$CA_CERT_PATH" >>"$CERT_FULLCHAIN_PATH"
  2465. _info "And the full chain certs is there: $(__green " $CERT_FULLCHAIN_PATH ")"
  2466. fi
  2467. Le_CertCreateTime=$(_time)
  2468. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  2469. Le_CertCreateTimeStr=$(date -u)
  2470. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  2471. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "$MAX_RENEW" ]; then
  2472. Le_RenewalDays="$MAX_RENEW"
  2473. else
  2474. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  2475. fi
  2476. if [ "$CA_BUNDLE" ]; then
  2477. _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
  2478. else
  2479. _clearaccountconf "CA_BUNDLE"
  2480. fi
  2481. if [ "$HTTPS_INSECURE" ]; then
  2482. _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
  2483. else
  2484. _clearaccountconf "HTTPS_INSECURE"
  2485. fi
  2486. if [ "$Le_Listen_V4" ]; then
  2487. _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
  2488. _cleardomainconf Le_Listen_V6
  2489. elif [ "$Le_Listen_V6" ]; then
  2490. _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
  2491. _cleardomainconf Le_Listen_V4
  2492. fi
  2493. Le_NextRenewTime=$(_math "$Le_CertCreateTime" + "$Le_RenewalDays" \* 24 \* 60 \* 60)
  2494. Le_NextRenewTimeStr=$(_time2str "$Le_NextRenewTime")
  2495. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  2496. Le_NextRenewTime=$(_math "$Le_NextRenewTime" - 86400)
  2497. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  2498. _on_issue_success
  2499. if [ "$Le_RealCertPath$Le_RealKeyPath$Le_RealCACertPath$Le_ReloadCmd$Le_RealFullChainPath" ]; then
  2500. _installcert
  2501. fi
  2502. }
  2503. #domain [isEcc]
  2504. renew() {
  2505. Le_Domain="$1"
  2506. if [ -z "$Le_Domain" ]; then
  2507. _usage "Usage: $PROJECT_ENTRY --renew -d domain.com [--ecc]"
  2508. return 1
  2509. fi
  2510. _isEcc="$2"
  2511. _initpath "$Le_Domain" "$_isEcc"
  2512. _info "$(__green "Renew: '$Le_Domain'")"
  2513. if [ ! -f "$DOMAIN_CONF" ]; then
  2514. _info "'$Le_Domain' is not a issued domain, skip."
  2515. return 0
  2516. fi
  2517. if [ "$Le_RenewalDays" ]; then
  2518. _savedomainconf Le_RenewalDays "$Le_RenewalDays"
  2519. fi
  2520. . "$DOMAIN_CONF"
  2521. if [ "$Le_API" ]; then
  2522. API="$Le_API"
  2523. fi
  2524. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  2525. _info "Skip, Next renewal time is: $(__green "$Le_NextRenewTimeStr")"
  2526. _info "Add '$(__red '--force')' to force to renew."
  2527. return "$RENEW_SKIP"
  2528. fi
  2529. IS_RENEW="1"
  2530. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath" "$Le_PreHook" "$Le_PostHook" "$Le_RenewHook" "$Le_LocalAddress"
  2531. res="$?"
  2532. if [ "$res" != "0" ]; then
  2533. return "$res"
  2534. fi
  2535. if [ "$Le_DeployHook" ]; then
  2536. deploy "$Le_Domain" "$Le_DeployHook" "$Le_Keylength"
  2537. res="$?"
  2538. fi
  2539. IS_RENEW=""
  2540. return "$res"
  2541. }
  2542. #renewAll [stopRenewOnError]
  2543. renewAll() {
  2544. _initpath
  2545. _stopRenewOnError="$1"
  2546. _debug "_stopRenewOnError" "$_stopRenewOnError"
  2547. _ret="0"
  2548. for di in "${CERT_HOME}"/*.*/; do
  2549. _debug di "$di"
  2550. if ! [ -d "$di" ]; then
  2551. _debug "Not directory, skip: $di"
  2552. continue
  2553. fi
  2554. d=$(basename "$di")
  2555. _debug d "$d"
  2556. (
  2557. if _endswith "$d" "$ECC_SUFFIX"; then
  2558. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  2559. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  2560. fi
  2561. renew "$d" "$_isEcc"
  2562. )
  2563. rc="$?"
  2564. _debug "Return code: $rc"
  2565. if [ "$rc" != "0" ]; then
  2566. if [ "$rc" = "$RENEW_SKIP" ]; then
  2567. _info "Skipped $d"
  2568. elif [ "$_stopRenewOnError" ]; then
  2569. _err "Error renew $d, stop now."
  2570. return "$rc"
  2571. else
  2572. _ret="$rc"
  2573. _err "Error renew $d, Go ahead to next one."
  2574. fi
  2575. fi
  2576. done
  2577. return "$_ret"
  2578. }
  2579. #csr webroot
  2580. signcsr() {
  2581. _csrfile="$1"
  2582. _csrW="$2"
  2583. if [ -z "$_csrfile" ] || [ -z "$_csrW" ]; then
  2584. _usage "Usage: $PROJECT_ENTRY --signcsr --csr mycsr.csr -w /path/to/webroot/a.com/ "
  2585. return 1
  2586. fi
  2587. _initpath
  2588. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  2589. if [ "$?" != "0" ]; then
  2590. _err "Can not read subject from csr: $_csrfile"
  2591. return 1
  2592. fi
  2593. _debug _csrsubj "$_csrsubj"
  2594. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  2595. if [ "$?" != "0" ]; then
  2596. _err "Can not read domain list from csr: $_csrfile"
  2597. return 1
  2598. fi
  2599. _debug "_csrdomainlist" "$_csrdomainlist"
  2600. if [ -z "$_csrsubj" ]; then
  2601. _csrsubj="$(_getfield "$_csrdomainlist" 1)"
  2602. _debug _csrsubj "$_csrsubj"
  2603. _csrdomainlist="$(echo "$_csrdomainlist" | cut -d , -f 2-)"
  2604. _debug "_csrdomainlist" "$_csrdomainlist"
  2605. fi
  2606. if [ -z "$_csrsubj" ]; then
  2607. _err "Can not read subject from csr: $_csrfile"
  2608. return 1
  2609. fi
  2610. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  2611. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  2612. _err "Can not read key length from csr: $_csrfile"
  2613. return 1
  2614. fi
  2615. _initpath "$_csrsubj" "$_csrkeylength"
  2616. mkdir -p "$DOMAIN_PATH"
  2617. _info "Copy csr to: $CSR_PATH"
  2618. cp "$_csrfile" "$CSR_PATH"
  2619. issue "$_csrW" "$_csrsubj" "$_csrdomainlist" "$_csrkeylength"
  2620. }
  2621. showcsr() {
  2622. _csrfile="$1"
  2623. _csrd="$2"
  2624. if [ -z "$_csrfile" ] && [ -z "$_csrd" ]; then
  2625. _usage "Usage: $PROJECT_ENTRY --showcsr --csr mycsr.csr"
  2626. return 1
  2627. fi
  2628. _initpath
  2629. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  2630. if [ "$?" != "0" ] || [ -z "$_csrsubj" ]; then
  2631. _err "Can not read subject from csr: $_csrfile"
  2632. return 1
  2633. fi
  2634. _info "Subject=$_csrsubj"
  2635. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  2636. if [ "$?" != "0" ]; then
  2637. _err "Can not read domain list from csr: $_csrfile"
  2638. return 1
  2639. fi
  2640. _debug "_csrdomainlist" "$_csrdomainlist"
  2641. _info "SubjectAltNames=$_csrdomainlist"
  2642. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  2643. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  2644. _err "Can not read key length from csr: $_csrfile"
  2645. return 1
  2646. fi
  2647. _info "KeyLength=$_csrkeylength"
  2648. }
  2649. list() {
  2650. _raw="$1"
  2651. _initpath
  2652. _sep="|"
  2653. if [ "$_raw" ]; then
  2654. printf "%s\n" "Main_Domain${_sep}KeyLength${_sep}SAN_Domains${_sep}Created${_sep}Renew"
  2655. for di in "${CERT_HOME}"/*.*/; do
  2656. if ! [ -d "$di" ]; then
  2657. _debug "Not directory, skip: $di"
  2658. continue
  2659. fi
  2660. d=$(basename "$di")
  2661. _debug d "$d"
  2662. (
  2663. if _endswith "$d" "$ECC_SUFFIX"; then
  2664. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  2665. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  2666. fi
  2667. _initpath "$d" "$_isEcc"
  2668. if [ -f "$DOMAIN_CONF" ]; then
  2669. . "$DOMAIN_CONF"
  2670. printf "%s\n" "$Le_Domain${_sep}\"$Le_Keylength\"${_sep}$Le_Alt${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr"
  2671. fi
  2672. )
  2673. done
  2674. else
  2675. if _exists column; then
  2676. list "raw" | column -t -s "$_sep"
  2677. else
  2678. list "raw" | tr "$_sep" '\t'
  2679. fi
  2680. fi
  2681. }
  2682. deploy() {
  2683. Le_Domain="$1"
  2684. Le_DeployHook="$2"
  2685. _isEcc="$3"
  2686. if [ -z "$Le_DeployHook" ]; then
  2687. _usage "Usage: $PROJECT_ENTRY --deploy -d domain.com --deploy-hook cpanel [--ecc] "
  2688. return 1
  2689. fi
  2690. _initpath "$Le_Domain" "$_isEcc"
  2691. if [ ! -d "$DOMAIN_PATH" ]; then
  2692. _err "Domain is not valid:'$Le_Domain'"
  2693. return 1
  2694. fi
  2695. _deployApi="$(_findHook "$Le_Domain" deploy "$Le_DeployHook")"
  2696. if [ -z "$_deployApi" ]; then
  2697. _err "The deploy hook $Le_DeployHook is not found."
  2698. return 1
  2699. fi
  2700. _debug _deployApi "$_deployApi"
  2701. _savedomainconf Le_DeployHook "$Le_DeployHook"
  2702. if ! (
  2703. if ! . "$_deployApi"; then
  2704. _err "Load file $_deployApi error. Please check your api file and try again."
  2705. return 1
  2706. fi
  2707. d_command="${Le_DeployHook}_deploy"
  2708. if ! _exists "$d_command"; then
  2709. _err "It seems that your api file is not correct, it must have a function named: $d_command"
  2710. return 1
  2711. fi
  2712. if ! $d_command "$Le_Domain" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$CERT_FULLCHAIN_PATH"; then
  2713. _err "Error deploy for domain:$Le_Domain"
  2714. _on_issue_err
  2715. return 1
  2716. fi
  2717. ); then
  2718. _err "Deploy error."
  2719. return 1
  2720. else
  2721. _info "$(__green Success)"
  2722. fi
  2723. }
  2724. installcert() {
  2725. Le_Domain="$1"
  2726. if [ -z "$Le_Domain" ]; then
  2727. _usage "Usage: $PROJECT_ENTRY --installcert -d domain.com [--ecc] [--certpath cert-file-path] [--keypath key-file-path] [--capath ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchainpath fullchain-path]"
  2728. return 1
  2729. fi
  2730. Le_RealCertPath="$2"
  2731. Le_RealKeyPath="$3"
  2732. Le_RealCACertPath="$4"
  2733. Le_ReloadCmd="$5"
  2734. Le_RealFullChainPath="$6"
  2735. _isEcc="$7"
  2736. _initpath "$Le_Domain" "$_isEcc"
  2737. if [ ! -d "$DOMAIN_PATH" ]; then
  2738. _err "Domain is not valid:'$Le_Domain'"
  2739. return 1
  2740. fi
  2741. _installcert
  2742. }
  2743. _installcert() {
  2744. _savedomainconf "Le_RealCertPath" "$Le_RealCertPath"
  2745. _savedomainconf "Le_RealCACertPath" "$Le_RealCACertPath"
  2746. _savedomainconf "Le_RealKeyPath" "$Le_RealKeyPath"
  2747. _savedomainconf "Le_ReloadCmd" "$Le_ReloadCmd"
  2748. _savedomainconf "Le_RealFullChainPath" "$Le_RealFullChainPath"
  2749. if [ "$Le_RealCertPath" = "$NO_VALUE" ]; then
  2750. Le_RealCertPath=""
  2751. fi
  2752. if [ "$Le_RealKeyPath" = "$NO_VALUE" ]; then
  2753. Le_RealKeyPath=""
  2754. fi
  2755. if [ "$Le_RealCACertPath" = "$NO_VALUE" ]; then
  2756. Le_RealCACertPath=""
  2757. fi
  2758. if [ "$Le_ReloadCmd" = "$NO_VALUE" ]; then
  2759. Le_ReloadCmd=""
  2760. fi
  2761. if [ "$Le_RealFullChainPath" = "$NO_VALUE" ]; then
  2762. Le_RealFullChainPath=""
  2763. fi
  2764. if [ "$Le_RealCertPath" ]; then
  2765. _info "Installing cert to:$Le_RealCertPath"
  2766. if [ -f "$Le_RealCertPath" ] && [ ! "$IS_RENEW" ]; then
  2767. cp "$Le_RealCertPath" "$Le_RealCertPath".bak
  2768. fi
  2769. cat "$CERT_PATH" >"$Le_RealCertPath"
  2770. fi
  2771. if [ "$Le_RealCACertPath" ]; then
  2772. _info "Installing CA to:$Le_RealCACertPath"
  2773. if [ "$Le_RealCACertPath" = "$Le_RealCertPath" ]; then
  2774. echo "" >>"$Le_RealCACertPath"
  2775. cat "$CA_CERT_PATH" >>"$Le_RealCACertPath"
  2776. else
  2777. if [ -f "$Le_RealCACertPath" ] && [ ! "$IS_RENEW" ]; then
  2778. cp "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  2779. fi
  2780. cat "$CA_CERT_PATH" >"$Le_RealCACertPath"
  2781. fi
  2782. fi
  2783. if [ "$Le_RealKeyPath" ]; then
  2784. _info "Installing key to:$Le_RealKeyPath"
  2785. if [ -f "$Le_RealKeyPath" ] && [ ! "$IS_RENEW" ]; then
  2786. cp "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  2787. fi
  2788. cat "$CERT_KEY_PATH" >"$Le_RealKeyPath"
  2789. fi
  2790. if [ "$Le_RealFullChainPath" ]; then
  2791. _info "Installing full chain to:$Le_RealFullChainPath"
  2792. if [ -f "$Le_RealFullChainPath" ] && [ ! "$IS_RENEW" ]; then
  2793. cp "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
  2794. fi
  2795. cat "$CERT_FULLCHAIN_PATH" >"$Le_RealFullChainPath"
  2796. fi
  2797. if [ "$Le_ReloadCmd" ]; then
  2798. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  2799. if (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd"); then
  2800. _info "$(__green "Reload success")"
  2801. else
  2802. _err "Reload error for :$Le_Domain"
  2803. fi
  2804. fi
  2805. }
  2806. installcronjob() {
  2807. _initpath
  2808. if ! _exists "crontab"; then
  2809. _err "crontab doesn't exist, so, we can not install cron jobs."
  2810. _err "All your certs will not be renewed automatically."
  2811. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  2812. return 1
  2813. fi
  2814. _info "Installing cron job"
  2815. if ! crontab -l | grep "$PROJECT_ENTRY --cron"; then
  2816. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ]; then
  2817. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  2818. else
  2819. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  2820. return 1
  2821. fi
  2822. if _exists uname && uname -a | grep solaris >/dev/null; then
  2823. crontab -l | {
  2824. cat
  2825. echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  2826. } | crontab --
  2827. else
  2828. crontab -l | {
  2829. cat
  2830. echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  2831. } | crontab -
  2832. fi
  2833. fi
  2834. if [ "$?" != "0" ]; then
  2835. _err "Install cron job failed. You need to manually renew your certs."
  2836. _err "Or you can add cronjob by yourself:"
  2837. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  2838. return 1
  2839. fi
  2840. }
  2841. uninstallcronjob() {
  2842. if ! _exists "crontab"; then
  2843. return
  2844. fi
  2845. _info "Removing cron job"
  2846. cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
  2847. if [ "$cr" ]; then
  2848. if _exists uname && uname -a | grep solaris >/dev/null; then
  2849. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab --
  2850. else
  2851. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
  2852. fi
  2853. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  2854. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  2855. fi
  2856. _initpath
  2857. }
  2858. revoke() {
  2859. Le_Domain="$1"
  2860. if [ -z "$Le_Domain" ]; then
  2861. _usage "Usage: $PROJECT_ENTRY --revoke -d domain.com"
  2862. return 1
  2863. fi
  2864. _isEcc="$2"
  2865. _initpath "$Le_Domain" "$_isEcc"
  2866. if [ ! -f "$DOMAIN_CONF" ]; then
  2867. _err "$Le_Domain is not a issued domain, skip."
  2868. return 1
  2869. fi
  2870. if [ ! -f "$CERT_PATH" ]; then
  2871. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  2872. return 1
  2873. fi
  2874. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}" | tr -d "\r\n" | _urlencode)"
  2875. if [ -z "$cert" ]; then
  2876. _err "Cert for $Le_Domain is empty found, skip."
  2877. return 1
  2878. fi
  2879. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  2880. uri="$API/acme/revoke-cert"
  2881. if [ -f "$CERT_KEY_PATH" ]; then
  2882. _info "Try domain key first."
  2883. if _send_signed_request "$uri" "$data" "" "$CERT_KEY_PATH"; then
  2884. if [ -z "$response" ]; then
  2885. _info "Revoke success."
  2886. rm -f "$CERT_PATH"
  2887. return 0
  2888. else
  2889. _err "Revoke error by domain key."
  2890. _err "$response"
  2891. fi
  2892. fi
  2893. else
  2894. _info "Domain key file doesn't exists."
  2895. fi
  2896. _info "Try account key."
  2897. if _send_signed_request "$uri" "$data" "" "$ACCOUNT_KEY_PATH"; then
  2898. if [ -z "$response" ]; then
  2899. _info "Revoke success."
  2900. rm -f "$CERT_PATH"
  2901. return 0
  2902. else
  2903. _err "Revoke error."
  2904. _debug "$response"
  2905. fi
  2906. fi
  2907. return 1
  2908. }
  2909. #domain vtype
  2910. _deactivate() {
  2911. _d_domain="$1"
  2912. _d_type="$2"
  2913. _initpath
  2914. _d_i=0
  2915. _d_max_retry=9
  2916. while [ "$_d_i" -lt "$_d_max_retry" ]; do
  2917. _info "Deactivate: $_d_domain"
  2918. _d_i="$(_math $_d_i + 1)"
  2919. if ! __get_domain_new_authz "$_d_domain"; then
  2920. _err "Can not get domain new authz token."
  2921. return 1
  2922. fi
  2923. authzUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  2924. _debug "authzUri" "$authzUri"
  2925. if [ ! -z "$code" ] && [ ! "$code" = '201' ]; then
  2926. _err "new-authz error: $response"
  2927. return 1
  2928. fi
  2929. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"status":"valid","uri"[^\}]*')"
  2930. _debug entry "$entry"
  2931. if [ -z "$entry" ]; then
  2932. _info "No more valid entry found."
  2933. break
  2934. fi
  2935. _vtype="$(printf "%s\n" "$entry" | _egrep_o '"type": *"[^"]*"' | cut -d : -f 2 | tr -d '"')"
  2936. _debug _vtype "$_vtype"
  2937. _info "Found $_vtype"
  2938. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*' | cut -d : -f 2,3 | tr -d '"')"
  2939. _debug uri "$uri"
  2940. if [ "$_d_type" ] && [ "$_d_type" != "$_vtype" ]; then
  2941. _info "Skip $_vtype"
  2942. continue
  2943. fi
  2944. _info "Deactivate: $_vtype"
  2945. if ! _send_signed_request "$authzUri" "{\"resource\": \"authz\", \"status\":\"deactivated\"}"; then
  2946. _err "Can not deactivate $_vtype."
  2947. return 1
  2948. fi
  2949. _info "Deactivate: $_vtype success."
  2950. done
  2951. _debug "$_d_i"
  2952. if [ "$_d_i" -lt "$_d_max_retry" ]; then
  2953. _info "Deactivated success!"
  2954. else
  2955. _err "Deactivate failed."
  2956. fi
  2957. }
  2958. deactivate() {
  2959. _d_domain_list="$1"
  2960. _d_type="$2"
  2961. _initpath
  2962. _debug _d_domain_list "$_d_domain_list"
  2963. if [ -z "$(echo $_d_domain_list | cut -d , -f 1)" ]; then
  2964. _usage "Usage: $PROJECT_ENTRY --deactivate -d domain.com [-d domain.com]"
  2965. return 1
  2966. fi
  2967. for _d_dm in $(echo "$_d_domain_list" | tr ',' ' '); do
  2968. if [ -z "$_d_dm" ] || [ "$_d_dm" = "$NO_VALUE" ]; then
  2969. continue
  2970. fi
  2971. if ! _deactivate "$_d_dm" "$_d_type"; then
  2972. return 1
  2973. fi
  2974. done
  2975. }
  2976. # Detect profile file if not specified as environment variable
  2977. _detect_profile() {
  2978. if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
  2979. echo "$PROFILE"
  2980. return
  2981. fi
  2982. DETECTED_PROFILE=''
  2983. SHELLTYPE="$(basename "/$SHELL")"
  2984. if [ "$SHELLTYPE" = "bash" ]; then
  2985. if [ -f "$HOME/.bashrc" ]; then
  2986. DETECTED_PROFILE="$HOME/.bashrc"
  2987. elif [ -f "$HOME/.bash_profile" ]; then
  2988. DETECTED_PROFILE="$HOME/.bash_profile"
  2989. fi
  2990. elif [ "$SHELLTYPE" = "zsh" ]; then
  2991. DETECTED_PROFILE="$HOME/.zshrc"
  2992. fi
  2993. if [ -z "$DETECTED_PROFILE" ]; then
  2994. if [ -f "$HOME/.profile" ]; then
  2995. DETECTED_PROFILE="$HOME/.profile"
  2996. elif [ -f "$HOME/.bashrc" ]; then
  2997. DETECTED_PROFILE="$HOME/.bashrc"
  2998. elif [ -f "$HOME/.bash_profile" ]; then
  2999. DETECTED_PROFILE="$HOME/.bash_profile"
  3000. elif [ -f "$HOME/.zshrc" ]; then
  3001. DETECTED_PROFILE="$HOME/.zshrc"
  3002. fi
  3003. fi
  3004. if [ ! -z "$DETECTED_PROFILE" ]; then
  3005. echo "$DETECTED_PROFILE"
  3006. fi
  3007. }
  3008. _initconf() {
  3009. _initpath
  3010. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  3011. echo "#ACCOUNT_CONF_PATH=xxxx
  3012. #Account configurations:
  3013. #Here are the supported macros, uncomment them to make them take effect.
  3014. #ACCOUNT_EMAIL=aaa@example.com # the account email used to register account.
  3015. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  3016. #CERT_HOME=\"/path/to/cert/home\"
  3017. #LOG_FILE=\"$DEFAULT_LOG_FILE\"
  3018. #LOG_LEVEL=1
  3019. #AUTO_UPGRADE=\"1\"
  3020. #STAGE=1 # Use the staging api
  3021. #FORCE=1 # Force to issue cert
  3022. #DEBUG=1 # Debug mode
  3023. #NO_TIMESTAMP=1
  3024. #OPENSSL_BIN=openssl
  3025. #USER_AGENT=\"$USER_AGENT\"
  3026. #USER_PATH=
  3027. #dns api
  3028. #######################
  3029. #Cloudflare:
  3030. #api key
  3031. #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
  3032. #account email
  3033. #CF_Email=\"xxxx@sss.com\"
  3034. #######################
  3035. #Dnspod.cn:
  3036. #api key id
  3037. #DP_Id=\"1234\"
  3038. #api key
  3039. #DP_Key=\"sADDsdasdgdsf\"
  3040. #######################
  3041. #Cloudxns.com:
  3042. #CX_Key=\"1234\"
  3043. #
  3044. #CX_Secret=\"sADDsdasdgdsf\"
  3045. #######################
  3046. #Godaddy.com:
  3047. #GD_Key=\"sdfdsgdgdfdasfds\"
  3048. #
  3049. #GD_Secret=\"sADDsdasdfsdfdssdgdsf\"
  3050. #######################
  3051. #nsupdate:
  3052. #NSUPDATE_KEY=\"/path/to/update.key\"
  3053. #NSUPDATE_SERVER=\"192.168.0.1\"
  3054. #######################
  3055. #PowerDNS:
  3056. #PDNS_Url=\"http://ns.example.com:8081\"
  3057. #PDNS_ServerId=\"localhost\"
  3058. #PDNS_Token=\"0123456789ABCDEF\"
  3059. #PDNS_Ttl=60
  3060. #######################
  3061. #Amazon Route53:
  3062. #AWS_ACCESS_KEY_ID=XXXXXXXXXX
  3063. #AWS_SECRET_ACCESS_KEY=XXXXXXXXXXXXXXX
  3064. " >"$ACCOUNT_CONF_PATH"
  3065. fi
  3066. }
  3067. # nocron
  3068. _precheck() {
  3069. _nocron="$1"
  3070. if ! _exists "curl" && ! _exists "wget"; then
  3071. _err "Please install curl or wget first, we need to access http resources."
  3072. return 1
  3073. fi
  3074. if [ -z "$_nocron" ]; then
  3075. if ! _exists "crontab"; then
  3076. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  3077. _err "We need to set cron job to renew the certs automatically."
  3078. _err "Otherwise, your certs will not be able to be renewed automatically."
  3079. if [ -z "$FORCE" ]; then
  3080. _err "Please add '--force' and try install again to go without crontab."
  3081. _err "./$PROJECT_ENTRY --install --force"
  3082. return 1
  3083. fi
  3084. fi
  3085. fi
  3086. if ! _exists "$OPENSSL_BIN"; then
  3087. _err "Please install openssl first."
  3088. _err "We need openssl to generate keys."
  3089. return 1
  3090. fi
  3091. if ! _exists "nc"; then
  3092. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  3093. _err "We use nc for standalone server if you use standalone mode."
  3094. _err "If you don't use standalone mode, just ignore this warning."
  3095. fi
  3096. return 0
  3097. }
  3098. _setShebang() {
  3099. _file="$1"
  3100. _shebang="$2"
  3101. if [ -z "$_shebang" ]; then
  3102. _usage "Usage: file shebang"
  3103. return 1
  3104. fi
  3105. cp "$_file" "$_file.tmp"
  3106. echo "$_shebang" >"$_file"
  3107. sed -n 2,99999p "$_file.tmp" >>"$_file"
  3108. rm -f "$_file.tmp"
  3109. }
  3110. _installalias() {
  3111. _initpath
  3112. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  3113. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ]; then
  3114. echo "$(cat "$_envfile")" | sed "s|^LE_WORKING_DIR.*$||" >"$_envfile"
  3115. echo "$(cat "$_envfile")" | sed "s|^alias le.*$||" >"$_envfile"
  3116. echo "$(cat "$_envfile")" | sed "s|^alias le.sh.*$||" >"$_envfile"
  3117. fi
  3118. _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  3119. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  3120. _profile="$(_detect_profile)"
  3121. if [ "$_profile" ]; then
  3122. _debug "Found profile: $_profile"
  3123. _info "Installing alias to '$_profile'"
  3124. _setopt "$_profile" ". \"$_envfile\""
  3125. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  3126. else
  3127. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  3128. fi
  3129. #for csh
  3130. _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
  3131. _csh_profile="$HOME/.cshrc"
  3132. if [ -f "$_csh_profile" ]; then
  3133. _info "Installing alias to '$_csh_profile'"
  3134. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  3135. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  3136. _setopt "$_csh_profile" "source \"$_cshfile\""
  3137. fi
  3138. #for tcsh
  3139. _tcsh_profile="$HOME/.tcshrc"
  3140. if [ -f "$_tcsh_profile" ]; then
  3141. _info "Installing alias to '$_tcsh_profile'"
  3142. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  3143. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  3144. _setopt "$_tcsh_profile" "source \"$_cshfile\""
  3145. fi
  3146. }
  3147. # nocron
  3148. install() {
  3149. if [ -z "$LE_WORKING_DIR" ]; then
  3150. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  3151. fi
  3152. _nocron="$1"
  3153. if ! _initpath; then
  3154. _err "Install failed."
  3155. return 1
  3156. fi
  3157. if [ "$_nocron" ]; then
  3158. _debug "Skip install cron job"
  3159. fi
  3160. if ! _precheck "$_nocron"; then
  3161. _err "Pre-check failed, can not install."
  3162. return 1
  3163. fi
  3164. #convert from le
  3165. if [ -d "$HOME/.le" ]; then
  3166. for envfile in "le.env" "le.sh.env"; do
  3167. if [ -f "$HOME/.le/$envfile" ]; then
  3168. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null; then
  3169. _upgrading="1"
  3170. _info "You are upgrading from le.sh"
  3171. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  3172. mv "$HOME/.le" "$LE_WORKING_DIR"
  3173. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  3174. break
  3175. fi
  3176. fi
  3177. done
  3178. fi
  3179. _info "Installing to $LE_WORKING_DIR"
  3180. if ! mkdir -p "$LE_WORKING_DIR"; then
  3181. _err "Can not create working dir: $LE_WORKING_DIR"
  3182. return 1
  3183. fi
  3184. chmod 700 "$LE_WORKING_DIR"
  3185. cp "$PROJECT_ENTRY" "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  3186. if [ "$?" != "0" ]; then
  3187. _err "Install failed, can not copy $PROJECT_ENTRY"
  3188. return 1
  3189. fi
  3190. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  3191. _installalias
  3192. for subf in $_SUB_FOLDERS; do
  3193. if [ -d "$subf" ]; then
  3194. mkdir -p "$LE_WORKING_DIR/$subf"
  3195. cp "$subf"/* "$LE_WORKING_DIR"/"$subf"/
  3196. fi
  3197. done
  3198. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  3199. _initconf
  3200. fi
  3201. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ]; then
  3202. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  3203. fi
  3204. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ]; then
  3205. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  3206. fi
  3207. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ]; then
  3208. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  3209. fi
  3210. if [ -z "$_nocron" ]; then
  3211. installcronjob
  3212. fi
  3213. if [ -z "$NO_DETECT_SH" ]; then
  3214. #Modify shebang
  3215. if _exists bash; then
  3216. _info "Good, bash is found, so change the shebang to use bash as prefered."
  3217. _shebang='#!/usr/bin/env bash'
  3218. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  3219. for subf in $_SUB_FOLDERS; do
  3220. if [ -d "$LE_WORKING_DIR/$subf" ]; then
  3221. for _apifile in "$LE_WORKING_DIR/$subf/"*.sh; do
  3222. _setShebang "$_apifile" "$_shebang"
  3223. done
  3224. fi
  3225. done
  3226. fi
  3227. fi
  3228. _info OK
  3229. }
  3230. # nocron
  3231. uninstall() {
  3232. _nocron="$1"
  3233. if [ -z "$_nocron" ]; then
  3234. uninstallcronjob
  3235. fi
  3236. _initpath
  3237. _uninstallalias
  3238. rm -f "$LE_WORKING_DIR/$PROJECT_ENTRY"
  3239. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  3240. }
  3241. _uninstallalias() {
  3242. _initpath
  3243. _profile="$(_detect_profile)"
  3244. if [ "$_profile" ]; then
  3245. _info "Uninstalling alias from: '$_profile'"
  3246. text="$(cat "$_profile")"
  3247. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" >"$_profile"
  3248. fi
  3249. _csh_profile="$HOME/.cshrc"
  3250. if [ -f "$_csh_profile" ]; then
  3251. _info "Uninstalling alias from: '$_csh_profile'"
  3252. text="$(cat "$_csh_profile")"
  3253. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_csh_profile"
  3254. fi
  3255. _tcsh_profile="$HOME/.tcshrc"
  3256. if [ -f "$_tcsh_profile" ]; then
  3257. _info "Uninstalling alias from: '$_csh_profile'"
  3258. text="$(cat "$_tcsh_profile")"
  3259. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_tcsh_profile"
  3260. fi
  3261. }
  3262. cron() {
  3263. IN_CRON=1
  3264. _initpath
  3265. if [ "$AUTO_UPGRADE" = "1" ]; then
  3266. export LE_WORKING_DIR
  3267. (
  3268. if ! upgrade; then
  3269. _err "Cron:Upgrade failed!"
  3270. return 1
  3271. fi
  3272. )
  3273. . "$LE_WORKING_DIR/$PROJECT_ENTRY" >/dev/null
  3274. if [ -t 1 ]; then
  3275. __INTERACTIVE="1"
  3276. fi
  3277. _info "Auto upgraded to: $VER"
  3278. fi
  3279. renewAll
  3280. _ret="$?"
  3281. IN_CRON=""
  3282. exit $_ret
  3283. }
  3284. version() {
  3285. echo "$PROJECT"
  3286. echo "v$VER"
  3287. }
  3288. showhelp() {
  3289. _initpath
  3290. version
  3291. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  3292. Commands:
  3293. --help, -h Show this help message.
  3294. --version, -v Show version info.
  3295. --install Install $PROJECT_NAME to your system.
  3296. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  3297. --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT .
  3298. --issue Issue a cert.
  3299. --signcsr Issue a cert from an existing csr.
  3300. --deploy Deploy the cert to your server.
  3301. --installcert Install the issued cert to apache/nginx or any other server.
  3302. --renew, -r Renew a cert.
  3303. --renewAll Renew all the certs.
  3304. --revoke Revoke a cert.
  3305. --list List all the certs.
  3306. --showcsr Show the content of a csr.
  3307. --installcronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  3308. --uninstallcronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  3309. --cron Run cron job to renew all the certs.
  3310. --toPkcs Export the certificate and key to a pfx file.
  3311. --updateaccount Update account info.
  3312. --registeraccount Register account key.
  3313. --createAccountKey, -cak Create an account private key, professional use.
  3314. --createDomainKey, -cdk Create an domain private key, professional use.
  3315. --createCSR, -ccsr Create CSR , professional use.
  3316. --deactivate Deactivate the domain authz, professional use.
  3317. Parameters:
  3318. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  3319. --force, -f Used to force to install or force to renew a cert immediately.
  3320. --staging, --test Use staging server, just for test.
  3321. --debug Output debug info.
  3322. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  3323. --standalone Use standalone mode.
  3324. --tls Use standalone tls mode.
  3325. --apache Use apache mode.
  3326. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  3327. --dnssleep [$DEFAULT_DNS_SLEEP] The time in seconds to wait for all the txt records to take effect in dns api mode. Default $DEFAULT_DNS_SLEEP seconds.
  3328. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  3329. --accountkeylength, -ak [2048] Specifies the account key length.
  3330. --log [/path/to/logfile] Specifies the log file. The default is: \"$DEFAULT_LOG_FILE\" if you don't give a file path here.
  3331. --log-level 1|2 Specifies the log level, default is 1.
  3332. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  3333. --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
  3334. --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
  3335. --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
  3336. --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
  3337. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  3338. --accountconf Specifies a customized account config file.
  3339. --home Specifies the home dir for $PROJECT_NAME .
  3340. --certhome Specifies the home dir to save all the certs, only valid for '--install' command.
  3341. --useragent Specifies the user agent string. it will be saved for future use too.
  3342. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  3343. --accountkey Specifies the account key path, Only valid for the '--install' command.
  3344. --days Specifies the days to renew the cert when using '--issue' command. The max value is $MAX_RENEW days.
  3345. --httpport Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
  3346. --tlsport Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
  3347. --local-address Specifies the standalone/tls server listening address, in case you have multiple ip addresses.
  3348. --listraw Only used for '--list' command, list the certs in raw format.
  3349. --stopRenewOnError, -se Only valid for '--renewall' command. Stop if one cert has error in renewal.
  3350. --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
  3351. --ca-bundle Specifices the path to the CA certificate bundle to verify api server's certificate.
  3352. --nocron Only valid for '--install' command, which means: do not install the default cron job. In this case, the certs will not be renewed automatically.
  3353. --ecc Specifies to use the ECC cert. Valid for '--installcert', '--renew', '--revoke', '--toPkcs' and '--createCSR'
  3354. --csr Specifies the input csr.
  3355. --pre-hook Command to be run before obtaining any certificates.
  3356. --post-hook Command to be run after attempting to obtain/renew certificates. No matter the obain/renew is success or failed.
  3357. --renew-hook Command to be run once for each successfully renewed certificate.
  3358. --deploy-hook The hook file to deploy cert
  3359. --ocsp-must-staple, --ocsp Generate ocsp must Staple extension.
  3360. --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future.
  3361. --listen-v4 Force standalone/tls server to listen at ipv4.
  3362. --listen-v6 Force standalone/tls server to listen at ipv6.
  3363. --openssl-bin Specifies a custom openssl bin location.
  3364. "
  3365. }
  3366. # nocron
  3367. _installOnline() {
  3368. _info "Installing from online archive."
  3369. _nocron="$1"
  3370. if [ ! "$BRANCH" ]; then
  3371. BRANCH="master"
  3372. fi
  3373. target="$PROJECT/archive/$BRANCH.tar.gz"
  3374. _info "Downloading $target"
  3375. localname="$BRANCH.tar.gz"
  3376. if ! _get "$target" >$localname; then
  3377. _err "Download error."
  3378. return 1
  3379. fi
  3380. (
  3381. _info "Extracting $localname"
  3382. tar xzf $localname
  3383. cd "$PROJECT_NAME-$BRANCH"
  3384. chmod +x $PROJECT_ENTRY
  3385. if ./$PROJECT_ENTRY install "$_nocron"; then
  3386. _info "Install success!"
  3387. fi
  3388. cd ..
  3389. rm -rf "$PROJECT_NAME-$BRANCH"
  3390. rm -f "$localname"
  3391. )
  3392. }
  3393. upgrade() {
  3394. if (
  3395. _initpath
  3396. export LE_WORKING_DIR
  3397. cd "$LE_WORKING_DIR"
  3398. _installOnline "nocron"
  3399. ); then
  3400. _info "Upgrade success!"
  3401. exit 0
  3402. else
  3403. _err "Upgrade failed!"
  3404. exit 1
  3405. fi
  3406. }
  3407. _processAccountConf() {
  3408. if [ "$_useragent" ]; then
  3409. _saveaccountconf "USER_AGENT" "$_useragent"
  3410. elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ]; then
  3411. _saveaccountconf "USER_AGENT" "$USER_AGENT"
  3412. fi
  3413. if [ "$_accountemail" ]; then
  3414. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  3415. elif [ "$ACCOUNT_EMAIL" ] && [ "$ACCOUNT_EMAIL" != "$DEFAULT_ACCOUNT_EMAIL" ]; then
  3416. _saveaccountconf "ACCOUNT_EMAIL" "$ACCOUNT_EMAIL"
  3417. fi
  3418. if [ "$_openssl_bin" ]; then
  3419. _saveaccountconf "OPENSSL_BIN" "$_openssl_bin"
  3420. elif [ "$OPENSSL_BIN" ] && [ "$OPENSSL_BIN" != "$DEFAULT_OPENSSL_BIN" ]; then
  3421. _saveaccountconf "OPENSSL_BIN" "$OPENSSL_BIN"
  3422. fi
  3423. if [ "$_auto_upgrade" ]; then
  3424. _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
  3425. elif [ "$AUTO_UPGRADE" ]; then
  3426. _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
  3427. fi
  3428. }
  3429. _process() {
  3430. _CMD=""
  3431. _domain=""
  3432. _altdomains="$NO_VALUE"
  3433. _webroot=""
  3434. _keylength=""
  3435. _accountkeylength=""
  3436. _certpath=""
  3437. _keypath=""
  3438. _capath=""
  3439. _fullchainpath=""
  3440. _reloadcmd=""
  3441. _password=""
  3442. _accountconf=""
  3443. _useragent=""
  3444. _accountemail=""
  3445. _accountkey=""
  3446. _certhome=""
  3447. _httpport=""
  3448. _tlsport=""
  3449. _dnssleep=""
  3450. _listraw=""
  3451. _stopRenewOnError=""
  3452. #_insecure=""
  3453. _ca_bundle=""
  3454. _nocron=""
  3455. _ecc=""
  3456. _csr=""
  3457. _pre_hook=""
  3458. _post_hook=""
  3459. _renew_hook=""
  3460. _deploy_hook=""
  3461. _logfile=""
  3462. _log=""
  3463. _local_address=""
  3464. _log_level=""
  3465. _auto_upgrade=""
  3466. _listen_v4=""
  3467. _listen_v6=""
  3468. _openssl_bin=""
  3469. while [ ${#} -gt 0 ]; do
  3470. case "${1}" in
  3471. --help | -h)
  3472. showhelp
  3473. return
  3474. ;;
  3475. --version | -v)
  3476. version
  3477. return
  3478. ;;
  3479. --install)
  3480. _CMD="install"
  3481. ;;
  3482. --uninstall)
  3483. _CMD="uninstall"
  3484. ;;
  3485. --upgrade)
  3486. _CMD="upgrade"
  3487. ;;
  3488. --issue)
  3489. _CMD="issue"
  3490. ;;
  3491. --deploy)
  3492. _CMD="deploy"
  3493. ;;
  3494. --signcsr)
  3495. _CMD="signcsr"
  3496. ;;
  3497. --showcsr)
  3498. _CMD="showcsr"
  3499. ;;
  3500. --installcert | -i)
  3501. _CMD="installcert"
  3502. ;;
  3503. --renew | -r)
  3504. _CMD="renew"
  3505. ;;
  3506. --renewAll | --renewall)
  3507. _CMD="renewAll"
  3508. ;;
  3509. --revoke)
  3510. _CMD="revoke"
  3511. ;;
  3512. --list)
  3513. _CMD="list"
  3514. ;;
  3515. --installcronjob)
  3516. _CMD="installcronjob"
  3517. ;;
  3518. --uninstallcronjob)
  3519. _CMD="uninstallcronjob"
  3520. ;;
  3521. --cron)
  3522. _CMD="cron"
  3523. ;;
  3524. --toPkcs)
  3525. _CMD="toPkcs"
  3526. ;;
  3527. --createAccountKey | --createaccountkey | -cak)
  3528. _CMD="createAccountKey"
  3529. ;;
  3530. --createDomainKey | --createdomainkey | -cdk)
  3531. _CMD="createDomainKey"
  3532. ;;
  3533. --createCSR | --createcsr | -ccr)
  3534. _CMD="createCSR"
  3535. ;;
  3536. --deactivate)
  3537. _CMD="deactivate"
  3538. ;;
  3539. --updateaccount)
  3540. _CMD="updateaccount"
  3541. ;;
  3542. --registeraccount)
  3543. _CMD="registeraccount"
  3544. ;;
  3545. --domain | -d)
  3546. _dvalue="$2"
  3547. if [ "$_dvalue" ]; then
  3548. if _startswith "$_dvalue" "-"; then
  3549. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  3550. return 1
  3551. fi
  3552. if _is_idn "$_dvalue" && ! _exists idn; then
  3553. _err "It seems that $_dvalue is an IDN( Internationalized Domain Names), please install 'idn' command first."
  3554. return 1
  3555. fi
  3556. if [ -z "$_domain" ]; then
  3557. _domain="$_dvalue"
  3558. else
  3559. if [ "$_altdomains" = "$NO_VALUE" ]; then
  3560. _altdomains="$_dvalue"
  3561. else
  3562. _altdomains="$_altdomains,$_dvalue"
  3563. fi
  3564. fi
  3565. fi
  3566. shift
  3567. ;;
  3568. --force | -f)
  3569. FORCE="1"
  3570. ;;
  3571. --staging | --test)
  3572. STAGE="1"
  3573. ;;
  3574. --debug)
  3575. if [ -z "$2" ] || _startswith "$2" "-"; then
  3576. DEBUG="1"
  3577. else
  3578. DEBUG="$2"
  3579. shift
  3580. fi
  3581. ;;
  3582. --webroot | -w)
  3583. wvalue="$2"
  3584. if [ -z "$_webroot" ]; then
  3585. _webroot="$wvalue"
  3586. else
  3587. _webroot="$_webroot,$wvalue"
  3588. fi
  3589. shift
  3590. ;;
  3591. --standalone)
  3592. wvalue="$NO_VALUE"
  3593. if [ -z "$_webroot" ]; then
  3594. _webroot="$wvalue"
  3595. else
  3596. _webroot="$_webroot,$wvalue"
  3597. fi
  3598. ;;
  3599. --local-address)
  3600. lvalue="$2"
  3601. _local_address="$_local_address$lvalue,"
  3602. shift
  3603. ;;
  3604. --apache)
  3605. wvalue="apache"
  3606. if [ -z "$_webroot" ]; then
  3607. _webroot="$wvalue"
  3608. else
  3609. _webroot="$_webroot,$wvalue"
  3610. fi
  3611. ;;
  3612. --tls)
  3613. wvalue="$W_TLS"
  3614. if [ -z "$_webroot" ]; then
  3615. _webroot="$wvalue"
  3616. else
  3617. _webroot="$_webroot,$wvalue"
  3618. fi
  3619. ;;
  3620. --dns)
  3621. wvalue="dns"
  3622. if ! _startswith "$2" "-"; then
  3623. wvalue="$2"
  3624. shift
  3625. fi
  3626. if [ -z "$_webroot" ]; then
  3627. _webroot="$wvalue"
  3628. else
  3629. _webroot="$_webroot,$wvalue"
  3630. fi
  3631. ;;
  3632. --dnssleep)
  3633. _dnssleep="$2"
  3634. Le_DNSSleep="$_dnssleep"
  3635. shift
  3636. ;;
  3637. --keylength | -k)
  3638. _keylength="$2"
  3639. shift
  3640. ;;
  3641. --accountkeylength | -ak)
  3642. _accountkeylength="$2"
  3643. shift
  3644. ;;
  3645. --certpath)
  3646. _certpath="$2"
  3647. shift
  3648. ;;
  3649. --keypath)
  3650. _keypath="$2"
  3651. shift
  3652. ;;
  3653. --capath)
  3654. _capath="$2"
  3655. shift
  3656. ;;
  3657. --fullchainpath)
  3658. _fullchainpath="$2"
  3659. shift
  3660. ;;
  3661. --reloadcmd | --reloadCmd)
  3662. _reloadcmd="$2"
  3663. shift
  3664. ;;
  3665. --password)
  3666. _password="$2"
  3667. shift
  3668. ;;
  3669. --accountconf)
  3670. _accountconf="$2"
  3671. ACCOUNT_CONF_PATH="$_accountconf"
  3672. shift
  3673. ;;
  3674. --home)
  3675. LE_WORKING_DIR="$2"
  3676. shift
  3677. ;;
  3678. --certhome)
  3679. _certhome="$2"
  3680. CERT_HOME="$_certhome"
  3681. shift
  3682. ;;
  3683. --useragent)
  3684. _useragent="$2"
  3685. USER_AGENT="$_useragent"
  3686. shift
  3687. ;;
  3688. --accountemail)
  3689. _accountemail="$2"
  3690. ACCOUNT_EMAIL="$_accountemail"
  3691. shift
  3692. ;;
  3693. --accountkey)
  3694. _accountkey="$2"
  3695. ACCOUNT_KEY_PATH="$_accountkey"
  3696. shift
  3697. ;;
  3698. --days)
  3699. _days="$2"
  3700. Le_RenewalDays="$_days"
  3701. shift
  3702. ;;
  3703. --httpport)
  3704. _httpport="$2"
  3705. Le_HTTPPort="$_httpport"
  3706. shift
  3707. ;;
  3708. --tlsport)
  3709. _tlsport="$2"
  3710. Le_TLSPort="$_tlsport"
  3711. shift
  3712. ;;
  3713. --listraw)
  3714. _listraw="raw"
  3715. ;;
  3716. --stopRenewOnError | --stoprenewonerror | -se)
  3717. _stopRenewOnError="1"
  3718. ;;
  3719. --insecure)
  3720. #_insecure="1"
  3721. HTTPS_INSECURE="1"
  3722. ;;
  3723. --ca-bundle)
  3724. _ca_bundle="$(readlink -f "$2")"
  3725. CA_BUNDLE="$_ca_bundle"
  3726. shift
  3727. ;;
  3728. --nocron)
  3729. _nocron="1"
  3730. ;;
  3731. --ecc)
  3732. _ecc="isEcc"
  3733. ;;
  3734. --csr)
  3735. _csr="$2"
  3736. shift
  3737. ;;
  3738. --pre-hook)
  3739. _pre_hook="$2"
  3740. shift
  3741. ;;
  3742. --post-hook)
  3743. _post_hook="$2"
  3744. shift
  3745. ;;
  3746. --renew-hook)
  3747. _renew_hook="$2"
  3748. shift
  3749. ;;
  3750. --deploy-hook)
  3751. _deploy_hook="$2"
  3752. shift
  3753. ;;
  3754. --ocsp-must-staple | --ocsp)
  3755. Le_OCSP_Stable="1"
  3756. ;;
  3757. --log | --logfile)
  3758. _log="1"
  3759. _logfile="$2"
  3760. if _startswith "$_logfile" '-'; then
  3761. _logfile=""
  3762. else
  3763. shift
  3764. fi
  3765. LOG_FILE="$_logfile"
  3766. if [ -z "$LOG_LEVEL" ]; then
  3767. LOG_LEVEL="$DEFAULT_LOG_LEVEL"
  3768. fi
  3769. ;;
  3770. --log-level)
  3771. _log_level="$2"
  3772. LOG_LEVEL="$_log_level"
  3773. shift
  3774. ;;
  3775. --auto-upgrade)
  3776. _auto_upgrade="$2"
  3777. if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-'; then
  3778. _auto_upgrade="1"
  3779. else
  3780. shift
  3781. fi
  3782. AUTO_UPGRADE="$_auto_upgrade"
  3783. ;;
  3784. --listen-v4)
  3785. _listen_v4="1"
  3786. Le_Listen_V4="$_listen_v4"
  3787. ;;
  3788. --listen-v6)
  3789. _listen_v6="1"
  3790. Le_Listen_V6="$_listen_v6"
  3791. ;;
  3792. --openssl-bin)
  3793. _openssl_bin="$2"
  3794. OPENSSL_BIN="$_openssl_bin"
  3795. ;;
  3796. *)
  3797. _err "Unknown parameter : $1"
  3798. return 1
  3799. ;;
  3800. esac
  3801. shift 1
  3802. done
  3803. if [ "${_CMD}" != "install" ]; then
  3804. __initHome
  3805. if [ "$_log" ]; then
  3806. if [ -z "$_logfile" ]; then
  3807. _logfile="$DEFAULT_LOG_FILE"
  3808. fi
  3809. fi
  3810. if [ "$_logfile" ]; then
  3811. _saveaccountconf "LOG_FILE" "$_logfile"
  3812. LOG_FILE="$_logfile"
  3813. fi
  3814. if [ "$_log_level" ]; then
  3815. _saveaccountconf "LOG_LEVEL" "$_log_level"
  3816. LOG_LEVEL="$_log_level"
  3817. fi
  3818. _processAccountConf
  3819. fi
  3820. _debug2 LE_WORKING_DIR "$LE_WORKING_DIR"
  3821. if [ "$DEBUG" ]; then
  3822. version
  3823. fi
  3824. case "${_CMD}" in
  3825. install) install "$_nocron" ;;
  3826. uninstall) uninstall "$_nocron" ;;
  3827. upgrade) upgrade ;;
  3828. issue)
  3829. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address"
  3830. ;;
  3831. deploy)
  3832. deploy "$_domain" "$_deploy_hook" "$_ecc"
  3833. ;;
  3834. signcsr)
  3835. signcsr "$_csr" "$_webroot"
  3836. ;;
  3837. showcsr)
  3838. showcsr "$_csr" "$_domain"
  3839. ;;
  3840. installcert)
  3841. installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_ecc"
  3842. ;;
  3843. renew)
  3844. renew "$_domain" "$_ecc"
  3845. ;;
  3846. renewAll)
  3847. renewAll "$_stopRenewOnError"
  3848. ;;
  3849. revoke)
  3850. revoke "$_domain" "$_ecc"
  3851. ;;
  3852. deactivate)
  3853. deactivate "$_domain,$_altdomains"
  3854. ;;
  3855. registeraccount)
  3856. registeraccount "$_accountkeylength"
  3857. ;;
  3858. updateaccount)
  3859. updateaccount
  3860. ;;
  3861. list)
  3862. list "$_listraw"
  3863. ;;
  3864. installcronjob) installcronjob ;;
  3865. uninstallcronjob) uninstallcronjob ;;
  3866. cron) cron ;;
  3867. toPkcs)
  3868. toPkcs "$_domain" "$_password" "$_ecc"
  3869. ;;
  3870. createAccountKey)
  3871. createAccountKey "$_accountkeylength"
  3872. ;;
  3873. createDomainKey)
  3874. createDomainKey "$_domain" "$_keylength"
  3875. ;;
  3876. createCSR)
  3877. createCSR "$_domain" "$_altdomains" "$_ecc"
  3878. ;;
  3879. *)
  3880. _err "Invalid command: $_CMD"
  3881. showhelp
  3882. return 1
  3883. ;;
  3884. esac
  3885. _ret="$?"
  3886. if [ "$_ret" != "0" ]; then
  3887. return $_ret
  3888. fi
  3889. if [ "${_CMD}" = "install" ]; then
  3890. if [ "$_log" ]; then
  3891. if [ -z "$LOG_FILE" ]; then
  3892. LOG_FILE="$DEFAULT_LOG_FILE"
  3893. fi
  3894. _saveaccountconf "LOG_FILE" "$LOG_FILE"
  3895. fi
  3896. if [ "$_log_level" ]; then
  3897. _saveaccountconf "LOG_LEVEL" "$_log_level"
  3898. fi
  3899. _processAccountConf
  3900. fi
  3901. }
  3902. if [ "$INSTALLONLINE" ]; then
  3903. INSTALLONLINE=""
  3904. _installOnline $BRANCH
  3905. exit
  3906. fi
  3907. main() {
  3908. [ -z "$1" ] && showhelp && return
  3909. if _startswith "$1" '-'; then _process "$@"; else "$@"; fi
  3910. }
  3911. main "$@"